开发者

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

开发者 https://www.devze.com 2023-04-01 12:42 出处:网络
How could I improve the perfo开发者_如何学Crmance of the following updates ? Post.find(id1).update_attributes(:my_field => value1)

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

精彩评论

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