Search code examples
mysqlsqlruby-on-railsruby-on-rails-3update-attributes

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


How could I improve the performance 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)

Solution

  • 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.