Created
September 20, 2013 08:45
-
-
Save vlado/6634867 to your computer and use it in GitHub Desktop.
ActiveRecord: Enhanced Query Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hamed Asghari post: http://hasghari.github.io/2013/09/15/active-record-enhanced-query-objects.html | |
class PopularProductQuery | |
def initialize(relation = Product.scoped) | |
@relation = relation.extending(Scopes) | |
end | |
def popular(time) | |
@relation.with_recent_activity(time).with_available_reviews | |
end | |
module Scopes | |
def with_recent_activity(time) | |
joins(:reviews).where(reviews: { created_at: time..Time.now }) | |
end | |
def with_available_reviews | |
joins(:reviews).where(reviews: { available: true }) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment