我正在关注 Import CSV Railscast它是直截了当的。
问题在于它仅处理一个 csv 文件,该文件仅包含 1 个文件中 1 个模型中的信息。
比如说,我有一个 CSV 文件,我想将它导入到我的 Listing
模型。在每一行/列表中,它有一列名为 Building
其中该值实际上是该列表的建筑物属性的名称(即 @listing.building.name
)。
我如何处理导入中的这些情况?
这是瑞恩在 Railscast 中得到的壁橱,它位于 Product
模型在他的情况下:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
所发生的一切就是他正在检查产品是否存在,如果存在,则更新属性。如果没有,则创建一个新的。
不太确定在这种情况下如何处理关联......特别是考虑到需要发生的事情是在关联记录不存在的情况下,需要在此过程中创建它。
所以回到我的
building.name
前面的例子,如果没有 Building.find_by_name(name)
,那么它应该创建一个新的建筑记录。想法?
最佳答案
尝试这个
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
building = product.buildings.find_by_name(row['building_name'])
building ||= product.buildings.build
building.attributes = row.to_hash.slice(*build_accessible_attributes)
building.save!
end
end
更新:使用新的 rails 3 方法更新答案
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = where(id: row["id"])
.first_or_create!(row.to_hash.slice(*accessible_attributes))
product.buildings.where(name: row['building_name'])
.first_or_create!(row.to_hash.slice(*building_accessible_attributes))
end
end
关于ruby-on-rails - 导入 CSV 时,如何处理与关联对应的行中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14642121/