views:

27

answers:

2

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 do it?

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

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.

ScottD