Rails Associations has_one Latest Record

To get the last on a has_many, you would want to do something similar to @jvnill, except add a scope with an ordering to the association:

has_one :current_revision, -> { order created_at: :desc }, 
  class_name: 'SectionRevision', foreign_key: :section_id

This will ensure you get the most recent revision from the database.


You can change it to an association but normally, ordering for has_one or belongs_to association are always interpreted wrongly when used on queries. In your question, when you turn that into an association, that would be

has_one :current_revision, class_name: 'SectionRevision', foreign_key: :section_id, order: 'created_at DESC'

The problem with this is that when you try to combine this with other queries, it will normally give you the wrong record.

>> record.current_revision
   # gives you the last revision
>> record.joins(:current_revision).where(section_revisions: { id: 1 })
   # searches for the revision where the id is 1 ordered by created_at DESC

So I suggest you to add a current_revision_id instead.