假设一个模型具有以下标头( ID,Name ),但另一个具有其他标头(例如,但不限于( ID,Name,Price,Location ))的CSV文件。如何更改Model.rb文件以跳过不存在的头文件?
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发布于 2015-10-24 23:29:25
下面的代码将创建新产品或编辑现有产品。您可以在find_or_create_by块中添加所需的属性。
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
self.find_or_create_by(id: row["id"]) do |product|
product.name = row["name"]
end
end
end如果你只需要id和name,你可以在Rails4中这样做。
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
self.where(:id => row["id"], :name => row["name"]).first_or_create
end
endhttps://stackoverflow.com/questions/33319304
复制相似问题