Skip to content

Instantly share code, notes, and snippets.

@vlado
Created September 20, 2013 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlado/6634867 to your computer and use it in GitHub Desktop.
Save vlado/6634867 to your computer and use it in GitHub Desktop.
ActiveRecord: Enhanced Query Objects
# 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