Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Associations has_one Latest Record

Tags:

I have the following model:

class Section < ActiveRecord::Base   belongs_to :page   has_many :revisions, :class_name => 'SectionRevision', :foreign_key => 'section_id'   has_many :references    has_many :revisions, :class_name => 'SectionRevision',                         :foreign_key => 'section_id'    delegate :position, to: :current_revision    def current_revision     self.revisions.order('created_at DESC').first   end end 

Where current_revision is the most recently created revision. Is it possible to turn current_revision into an association so I can perform query like Section.where("current_revision.parent_section_id = '1'")? Or should I add a current_revision column to my database instead of trying to create it virtually or through associations?

like image 983
Ryan King Avatar asked Apr 05 '13 00:04

Ryan King


1 Answers

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.

like image 128
quainjn Avatar answered Sep 17 '22 09:09

quainjn