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?
Tag.increment_counter :popularity, id
Not only does this skip the select, but it increments atomically.
Maybe something like :
Tag.update_all("popularity = popularity + 1", {:id => id})
Or
Tag.where(:id => id).update_all("popularity = popularity + 1")
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With