Rails3 seed data nested attribute

前端 未结 1 1816
北海茫月
北海茫月 2021-01-06 05:51

What am I doing wrong here? The forms work but keep getting \"undefined method `to_i\' for :street1:Symbol\" when trying to seed data.

EDIT = If I do everyt

1条回答
  •  伪装坚强ぢ
    2021-01-06 06:45

    accepts_nested_attributes_for :foo is so that you can create forms which create associated records. When you're building things in code, there's no need to use this. You can create the associated records using the association names instead of "address_attributes". Here's one way of doing it, but Rails does expose a bunch of ways of doing this same thing...

    ["Company A", "Company B", "Company C", "Company D"].each do |c|
      vendor_address = Address.new :street1 => Faker::Address.street_address,
                                   :city => Faker::Address.city,
                                   :state => Faker::Address.us_state_abbr,
                                   :zipcode => Faker::Address.zip_code,
                                   :address_type => "Vendor"
    
      Vendor.create! :name => c,
                     :contact => Faker::Name.name,
                     :phone => Faker::PhoneNumber.phone_number,
                     :addresses => [vendor_address]
    end
    

    If you are wanting to try and use the nested attributes way, then you don't need the :vendor => {} part of the hash, you can go straight into the params, and you need addresses_attributes to be an array, not a hash.

    0 讨论(0)
提交回复
热议问题