So I have a method in my video model:
def rank_sum(score, video)
...
...
end
that returns a value that I want to store in my database for the specific video in the rank_sum column.
I also order my videos like so:
default_scope order('videos.rank_sum')
Now my question is how should I update the rank_sum column? With a callback? How often should I be updating this?
I’d recommend that you don’t create methods that clash with any of the automatically created attributes of your model, as this will interfere with built-in Rails functionality such as form generation.
You could simply rewrite your method as follows:
This will update the value in the database (if necessary) each time the
update_rank_summethod is called.If you want to postpone the update of the
rank_sumvalue until some later point, you can change the implementation as follows:But remember that you will need to call
saveon theVideoinstance to persist the change to the database.Updating one field of a single row is likely to take your database in the order of milliseconds, so I wouldn’t worry too much about performance unless you know you will need to handle 10s or 100s of changes per second.