当导入csv文件时,如何在2个模型之间批量分配? [英] How can I mass assign across 2 models when importing a csv file?

查看:224
本文介绍了当导入csv文件时,如何在2个模型之间批量分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用单个模型中的属性导入CSV文件并创建一个新对象(在这种情况下为列表)。

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

accepts_nested_attributes_for :address 


b $ b

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

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

我想我可以在导入CSV文件时从地址模型批量分配属性,但我得到错误:

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 

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

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

推荐答案

你的列表类定义改变你的导入方法:

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

这篇关于当导入csv文件时,如何在2个模型之间批量分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆