Update multiple records simultaneously with ActiveRecord in Rails using one query?

后端 未结 3 481
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 14:44

Let\'s suppose I have a table called \'user_products\' and a corresponding model called UserProduct in my Rails application. I also have a field called \'is_temporary\' in my ta

相关标签:
3条回答
  • 2021-02-05 14:49
    UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
    
    0 讨论(0)
  • 2021-02-05 14:56
    UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
    

    Although beware: this skips all validations and callbacks, since no instance of UserProduct will ever be instanciated.

    0 讨论(0)
  • 2021-02-05 15:02

    This is an old post. I updated this in case someone checks it :) (Rails 4)

    DEPRECATION: Relation#update_all with conditions is deprecated. Please use Item.where(color: 'red').update_all(...) rather than Item.update_all(..., color: 'red').
    

    So the query will be

    UserProduct.where(:user_id => 12345).update_all(:is_temporary => false)
    

    Cheers

    0 讨论(0)
提交回复
热议问题