Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 scopes inherited from other models

is there any way to use one model scopes as part of another model scope?

Example

class DocumentVersion < ActiveRecord::Base
  belongs_to :document
  scope :are_latest, lambda{ where(latest: true)}
end

class Document < ActiveRecord::Base
  has_many :document_versions
  scope :are_latest, lambda { ...something... } # I want something that will get documents that have documnet_versions that are_latest

  # I know I can do this 
  scope :are_latest,   lambda{ joins(:document_versions).where('document_versions.latest = true') }  # this works well

  # but I would like to keep that condition its own model
  scope :are_latest, lambda { joins(:document_versions).are_latest } # this wont obviously work, but something like that 

end
like image 629
equivalent8 Avatar asked Nov 30 '25 18:11

equivalent8


1 Answers

Yes you can use merge to combine scopes together.

class Document < ActiveRecord::Base
  has_many :document_versions

  scope :are_latest, lambda { joins(:document_versions).merge(DocumentVersion.are_latest) }
end
like image 184
Peter Brown Avatar answered Dec 03 '25 10:12

Peter Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!