Reputation: 12180
I have two tables as follows:
+-----+
Software
+-----+
id
name
latest_version [Field that needs to be implemented]
+-----+
Versions
+-----+
id
version_string
released_date
I have defined has_many :versions
in the Software
model and belongs_to :software
in the Version
model to associate them.
Now, the problem is I need to fetch the latest version based on the released date and store another reference in the Software table for faster lookups. So, how can I make the latest_version
column to refer a single row in the Version table with Rails? Or is it a bad practice?
UPDATE: I've already setup a named scope latest_version
in the Version model to fetch the latest version. However, I think this would not be the better option if the application scales (I think)
Upvotes: 2
Views: 123
Reputation: 1542
U can try caching as described in Ryan Bate's railscast episode on model caching. The gist of it is that u can store the latest_version_id as a cache in memory without having to create another column, or query the database each time the model is loaded.
The only time you need to query the database to get the latest version is
1) the first time when u cache the latest_version_id,
2) when the cache expires, or
3) when there is a new version, or
4) when a version is updated (someone key in the release date wrongly).
For 3 and 4, Ryan uses an after_save callback to expire the cache manually. What will happen thereafter is that the application will load and realises theres no cache for the latest_version_id, so it will query the database for it, using your scope method. In doing so it populate the cache again and the next time it need to load the latest version again, it does not query the database.
Upvotes: 1
Reputation: 1636
I think it would be semantically correct to change the name of the field to latest_version_id
.
You can then implement something like this.
has_one :latest_version, class_name: "Version", foreign_key: "latest_version_id"
or using a scope (not sure how you implemented that)
has_one :latest_version, -> { order 'created_at' }, class_name: "Version"
Upvotes: 3