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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With