Skip to content

Instantly share code, notes, and snippets.

@davidlowry
Created December 6, 2012 16:11
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 davidlowry/4225665 to your computer and use it in GitHub Desktop.
Save davidlowry/4225665 to your computer and use it in GitHub Desktop.
Rails 3 Scopes - Show Posts With Children Only
# this gets the last five "bookings"
scope :recent, lambda {|quantity| limit(5).order('id DESC')}
# I want to only fetch bookings that are valid for purchase, i.e. they have "festival tickets" reserved for campers.
# how do I get the five latest "bookings" _that have camper tickets_?
# ref - http://stackoverflow.com/questions/8250451/rails3-scope-for-count-of-children-in-has-many-relationship
scope :with_children, joins(:campers).
select('bookings.*').
group('bookings.id').
having('count(campers.name) > 0')
# So you can use
Booking.with_children.recent(5)
# Is there any tidier way to do the "has children" query scope than this?
# I'd like to do Booking.has_children(:campers).recent(5) for example
# Scopes are "obselete"
# according to http://www.elabs.se/blog/24-scopes-are-obsolete
# But does ActiveAdmin let you define Class.method_name? as a scope?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment