开发者

how to update_attributes with the conditions?

I need to update attributes but only for rows with the specific conditions like

["recipient_id = ? and inbox_id = ? and status='unread'", current_user.id, @inbox.id]

How do I d开发者_Python百科o it?


It depends on if you want to do a bulk SQL update, or do an update on each model that also calls validation and the normal callback chain.
If you want to instantiate the objects and run the callback chain do:

Model.find(:all, :conditions => ["recipient_id = ? and inbox_id = ? and status='unread'", current_user.id, @inbox.id]).each do |obj|
  obj.update_attributes(...)
end

If you want to do the SQL update:

Model.update_all("attr1='something', attr2=true,...",  ["recipient_id = ? and inbox_id = ? and status='unread'", current_user.id, @inbox.id])

Make sure to use the array form of conditions to ensure you correctly escape your SQL.


You can also do the bulk SQL update using where conditions, which I find to be more readable.

Model.where(recipient_id: current_user.id)
     .where(inbox_id: @inbox.id)
     .where(status: 'unread')
     .update_all("attr1='something_new'")


Model.update_all("foo='bar'", "recipient_id = #{current_user.id} and inbox_id = #{@inbox.id} and status='unread'")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜