开发者

How to update "my_field" of N posts in less than N queries?

How could I improve the perfo开发者_如何学Crmance of the following updates ?

Post.find(id1).update_attributes(:my_field => value1)
Post.find(id2).update_attributes(:my_field => value2)
Post.find(id3).update_attributes(:my_field => value3)
        ...                               ...
Post.find(idN).update_attributes(:my_field => valueN)


You can do it with a single SQL query using update_all

Post.update_all("field = 'value'", "id IN (id1, id2...)")

EDIT: This won't work with a single statement, of course you will have N Post.update_all sentences for N posts since each post will have different value, but since it makes and SQL UPDATE and doens't instantiate the Post objects is currently faster than Post.find.update_attributes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜