开发者

Ruby on Rails ActiveRecord: optimizing increment by one

开发者 https://www.devze.com 2023-02-13 12:02 出处:网络
I have an entry ID, which popularity has to be increased by one. A simple solution looks like thi开发者_JAVA百科s:

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

A simple solution looks like thi开发者_JAVA百科s:

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")

?

0

精彩评论

暂无评论...
验证码 换一张
取 消