4

In Ruby / Rails, how do I create a column in a table based on the value of two o...

 2 years ago
source link: https://www.codesd.com/item/in-ruby-rails-how-do-i-create-a-column-in-a-table-based-on-the-value-of-two-other-columns-in-the-same-table.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In Ruby / Rails, how do I create a column in a table based on the value of two other columns in the same table?

advertisements

I am trying to create a Reddit type app where the order of a list depends on a combination of the number of upvotes a link has and the created date. My plan is to create a new column in my "Links" table that combines "created_date" and "upvotes" into a "Rank Value" and then sort the list by the "Rank Value".

Is this the right approach? If so, how do I create this table column using ActiveRecord?


If there is a meta attribute that is used purely for display purposes, creating a method that will generate it on the fly would be appropriate.

If you want to use it for sorting your objects as well, it's better to store it in a column. Hopefully, it doesn't depend on things like the current time, and only on its other attributes:

before_save :calculate_rank

def calculate_rank
  self.rank = self.upvotes + self.clicks * 5;
end

Unfortunately, for your use case you specifically said your column depends on the creation date, probably in terms of "how fresh is it" -- a moving target.

You can solve this two ways: by constantly increasing the rank values for newer links indefinitely, or by putting items into time buckets and updating them periodically (degrading their scores when the day or week ends, perhaps).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK