0

I just added a new field to my Rails app which uses a MySQL DB. I have a CSV which contains values for the new field (name) for records already in the table.

Article (table)
_______________
id | name

In the first field of the CSV is the id field and in the second is the name. I want to update the Article table by updating the name field based on the id field in the CSV. Can someone please help me write a MySQL query for doing this?

4

1 回答 1

1
CSV.open('file_path.csv', 'r').each do |row|
  article = Article.find_by_id(row[0])

  article.update_attribute(:name, row[1]) if article
end

我使用它是find_by_id因为nil如果没有找到它就会返回,而find返回异常 ActiveRecord::recordNotFound。

于 2013-05-11T18:05:56.440 回答