Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Instead of creating another relationship, I would use a scope on <code>LessonVersion</code>.</p> <pre><code>class Lesson &lt; ActiveRecord::Base attr_accessible :number has_many :lesson_versions def most_recent_version lesson_versions.most_recent.first end end class LessonVersion &lt; ActiveRecord::Base attr_accessible :lesson_id, :version belongs_to :lesson scope :recent, order("created_at DESC") end </code></pre> <p>Also, you might prefer to order by <code>"version DESC"</code> if version is an integer that increases with each new version.</p> <p><strong>EDIT</strong>: After reading your comment, I have two suggestions.</p> <p><strong>Suggestion 1</strong></p> <p>Use my solution above, but with <code>"version DESC"</code> for the sort, and when you want to revert to an older version, instead duplicate it and make it the newest version. Then you have a history of all edits and don't need </p> <p>As for the order in the query, if you add a compound index on <code>version</code> and <code>lesson_id</code> in the database this will be a trivial operation. Also, calling <code>#first</code> on a scope is efficient, it will query with <code>LIMIT 1</code> and only instantiate the record you care about. And the result of the query is automatically cached if you need to use this method multiple times in the same request.</p> <p><strong>Suggestion 2</strong></p> <p>Set up a belongs_to on Lesson, but name it :current_version so as to prevent confusion.</p> <pre><code>class Lesson &lt; ActiveRecord::Base attr_accessible :number, :current_version_id has_many :lesson_versions belongs_to :current_version, :class_name =&gt; "LessonVersion" end class LessonVersion &lt; ActiveRecord::Base attr_accessible :lesson_id, :version belongs_to :lesson scope :recent, order("created_at DESC") end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload