How can I mass assign across 2 models when importing a csv file?

一笑奈何 提交于 2019-12-25 14:49:09

问题


I can import a CSV file and create a new object (listing in this case) using the attributes from a single model.

I put this in the Listing model

accepts_nested_attributes_for :address 

where address is an associated model (address has many listings, listing belongs to address).

I thought I'd then be able to mass assign attributes from the address model also when importing the CSV file but I get the error:

Can't mass-assign protected attributes: unit_number 

where unit_number in one of the attributes in the address model (it's in attr accessible).


回答1:


in your Listing class definition change your import method:

def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Listing.create!( :price => row[0], :status => row[1], 
                       :beds => row[2], :baths => row[3], 
                       :address_attributes => {:unit_number => row[4]} ) 
    end
end


来源:https://stackoverflow.com/questions/15147777/how-can-i-mass-assign-across-2-models-when-importing-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!