2012-11-06 62 views
2

是否有任何方式使用一個模型範圍作爲另一個模型範圍的一部分?從其他模型繼承的軌道3範圍

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 

回答

2

是的,你可以使用merge到示波器結合在一起。

class Document < ActiveRecord::Base 
    has_many :document_versions 

    scope :are_latest, lambda { joins(:document_versions).merge(DocumentVersion.are_latest) } 
end 
+0

:)真的很酷,完美的作品thx – equivalent8