ruby-on-rails - 导入 CSV 时,如何处理与关联对应的行中的数据?

标签 ruby-on-rails ruby-on-rails-3 csv import

我正在关注 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/

相关文章:

javascript - 应用程序内的 Rails 搜索选项

sql - ActiveRecord .missing - 为什么这不起作用?

ruby-on-rails - Ruby on Rails : How do I correctly define a method in the model to total up a column?

ruby-on-rails - rails 中是否有 options_for_select 的分隔符?

ruby - 从服务器上的 CSV 复制到 PostgreSQL 数据库

objective-c - 在 Mac 应用程序和 Web 之间同步 'lot' 小块数据的最佳方法是什么?

ruby-on-rails - 在 form_for 中选择没有秒、分钟或小时的 Datetime_select

ruby-on-rails - 在模型中,什么时候使用attr_accessor,什么时候使用attr_accessible?

csv - 在 Rust 中使用带有 serde 的嵌套枚举/结构序列化/反序列化 CSV

python-3.x - Pytest 创建临时 CSV 文件以供读取