2013-02-28 20 views
0

我可以導入CSV文件,並使用單個模型中的屬性創建一個新對象(本例中列出)。導入csv文件時如何跨2個模型進行批量分配?

我把這個上市模型

accepts_nested_attributes_for :address 

,其中地址是相關的模型(地址有許多房源,房源屬於地址)。

我當時認爲我能夠大規模從分配地址模型導入CSV文件時,還會爲屬性,但我得到的錯誤:

Can't mass-assign protected attributes: unit_number 

其中unit_number在地址模型的屬性之一(它在attr訪問)。

+0

可以更新的問題,並把這些模型與它的關係,你寫的代碼attr_accessible? – rorra 2013-02-28 23:40:57

+0

您是否還可以提供用於從CSV中進行分配的代碼? – moonfly 2013-03-01 00:02:37

+0

您是否想在創建列表時創建新地址? – 2013-03-01 00:07:09

回答

4

在上市類定義更改導入方法:

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 
+0

@MichaeleRomano它將創建只有unit_number的地址記錄,所有其他字段將爲空。 :) – 2013-03-01 00:23:58

+0

謝謝!!!我知道我錯過了在我面前的事情! – mano26 2013-03-01 00:30:31

+1

@SybariteManoj,正確。 @Michael Romano,從這裏開始,並不斷添加CSV中的屬性。例如。如果你在CSV的第[5]行有'city',只要將address_attributes行改爲':address_attributes => {:unit_number => row [4],:city => row [5]}'等等,等等。 – moonfly 2013-03-01 00:31:14