baash05
baash05

Reputation: 4516

get the changed records from an update all in ruby

In postgresql this works

update products set status = 1 
where status <> 1 and updated_at < '2014-04-01'
returning id;

This is most handy because I get the id's of all the records I've just updated.

Is there a way to do this in active record?
I am trying (very hard) to be more of a ruby guy.
I am finding the leaky abstraction in cases like this a bit hard.

I understand that update_all returns the count.
Is there a call that allows for the returning?

Upvotes: 0

Views: 66

Answers (2)

Pavan
Pavan

Reputation: 33542

For Rails <4,you can write something like this

Product.where('updated_at < ? and status != ?', '2014-04-01', 1).map do |product|
product.update_attribute(:status, 1)
product.id

OR

Product.where('updated_at < ? and status NOT IN (?)', '2014-04-01', 1).map do |product|
product.update_attribute(:status, 1)
product.id

OR

Product.find(:all, :conditions => ['updated_at < ? and status NOT IN (?)', '2014-04-01', 1]).map do |product|
product.update_attribute(:status, 1)
product.id

Upvotes: 0

kiddorails
kiddorails

Reputation: 13014

For Rails 4:

Product.where('updated_at < ? and not status = ?', '2014-04-01', 1).map do |product|
  product.update_attribute(:status, 1)
  product.id
end

Upvotes: 1

Related Questions