Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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