Home > Software design >  Rails - How to use accepts nested attributes within .new (without saving to the database)
Rails - How to use accepts nested attributes within .new (without saving to the database)

Time:10-01

I want to build up a model without storing it in the database, but with accepting nested attributes. It appears that passing parameters with nested attributes to .new does not accept them, and just creates a new model, without any of the passed associations.

Is there a way to have .new accept nested attributes, or another method I can use to accomplish this?

Thanks!

CodePudding user response:

You're basing the entire question on a faulty premise.

class Company < ApplicationRecord
  has_many :products
  accepts_nested_attributes_for :products
end
class Product < ApplicationRecord
  belongs_to :company
end
irb(main):002:0> c = Company.new(name: 'Acme', products_attributes: [ { name: 'Anvil' }])
=> #<Company:0x000056417471c2b0 id: nil, name: "Acme", created_at: nil, updated_at: nil>
irb(main):003:0> c.products
=> [#<Product:0x0000564174972258 id: nil, name: "Anvil", company_id: nil, created_at: nil, updated_at: nil>]   

As you can see here the attributes are very much passed to .new - in fact thats exactly what the entire feature is supposed to do so it would be strange otherwise.

So whats actually going wrong? The most likely explaination is that you aren't whitelisting the parameters for the nested records. Make sure that you're using the correct pluralization - the parameter key is singular_attributes for belongs_to / has_one and plural_attributes for has_many/has_and_belongs_to_many.

  • Related