导入csv文件时,如何在2个模型中进行质量分配?

我可以使用单个模型中的属性导入CSV文件并创建一个新对象(在本例中列出)。

我把它放在了Listing模型中

accepts_nested_attributes_for :address 

其中address是关联模型(地址有很多列表,列表属于地址)。

我以为我能够在导入CSV文件时从地址模型中批量分配属性,但是我收到错误:

 Can't mass-assign protected attributes: unit_number 

其中unit_number在地址模型中的一个属性中(它在attr中可访问)。

在您的Listing类定义中更改导入方法:

 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