Created
December 6, 2012 16:11
-
-
Save davidlowry/4225665 to your computer and use it in GitHub Desktop.
Rails 3 Scopes - Show Posts With Children Only
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
# 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