开发者

update_all in rails - updating multiple rows using values from those rows

On rails 2.3.11

I'm trying to update multiple rows in a table with values from a different column in 开发者_StackOverflow社区each different row (specifically I'm adding timestamps to a table that already existed, using rails migrations).

At first I thought that update_all might work, but it seems that is only for updating multiple rows with the same value.

I resorted to using a SQL statement to get what I wanted (date is the column that already existed, which I am using as an initial value for my timestamps):

execute <<-SQL
  UPDATE tablename SET created_at = date;
SQL

Is there a better 'rails way' of doing this?


You should be able to reference another field in update_all. Your problem is most likely the fact that date is a SQL keyword.

See if this works:

Model.update_all('tablename.created_at = tablename.date')

If not you might have to quote date but it will be different in different databases.

MySQL:

Model.update_all('`created_at` = `date`')

SQLite:

Model.update_all('"created_at" = "date"')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜