Question

I have a Subscription model with a price field and my last migration introduced a field called per_month_price. I am looking for a method which can update records faster than a simple .each {...}. For example:

Subscription.update_all {|c| c.per_month_price = c.price/12}

Was it helpful?

Solution

why not simply use

Subscription.update_all( "per_month_price = price / 12" )

This is working. It takes the statement and runs for all found records. This is very common in rails.

http://apidock.com/rails/ActiveRecord/Relation/update_all

Please check before downvote!

OTHER TIPS

You can try to do it in raw sql. I'm not sure that the syntax is standard SQL, it may not work with all DBs

ActiveRecord::Base.connection.execute('UPDATE Subscription SET per_month_price = price / 12')

It seems ok with mySQL

Maybe I'm missing something, but why add it to the database at all if it can be determined programatically from an existing column? Just create a virtual attribute:

class Subscription < ActiveRecord::Base

  .
  .
  .

  def per_month_price
    self.price / 12
  end

  def per_month_price=(arg)
    self.price = arg*12
  end

end

This will function the same as if you had a per_month_price column in your DB. It'll be more efficient as you won't have to hit the database so much, and it eliminates the (very likely) possibility that the price and per_month_price columns will become inconsistent with eachother somewhere, e.g. if you update one but forget to update the other.

Sorry that I didn't directly answer your question (especially to anyone coming here through Google), but this seems like a much better design to me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top