Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails ActiveRecord: optimizing increment by one

I have an entry ID, which popularity has to be increased by one.

A simple solution looks like this:

Tag.find(id).increment!(:popularity)

However it doesn't seem to be very efficient, because I select the entire entry (*) from the database (even though I don't need it at all) and then do the second query to update it.

Is there a more efficient way to do this? I think, one update statement (without "select") should be enough, but how do I write this?

like image 493
krn Avatar asked Feb 24 '11 20:02

krn


2 Answers

Tag.increment_counter :popularity, id

Not only does this skip the select, but it increments atomically.

like image 79
idlefingers Avatar answered Oct 24 '22 17:10

idlefingers


Maybe something like :

Tag.update_all("popularity = popularity + 1", {:id => id})

Or

Tag.where(:id => id).update_all("popularity = popularity + 1")

?

like image 27
christianblais Avatar answered Oct 24 '22 17:10

christianblais