Created
June 25, 2014 14:39
-
-
Save ngauthier/372f504a83f269c5c727 to your computer and use it in GitHub Desktop.
ActiveRecord Scope Merging
This file contains hidden or 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
# Merging Scopes | |
# ============== | |
# The goal is to join two tables to get all the records where a scope on both | |
# side of the join is used. I used to do this with a `where()` in which I | |
# added some sql on the joined table. But, I wanted to use the existing scopes | |
# from the joining table. Turns out there's a `merge` method on a scope where | |
# you can merge with another scope without having to chain! | |
class Car < ActiveRecord::Base | |
has_and_belongs_to_many :people | |
scope :fueled, -> { where(fueled: true) } | |
end | |
class Person < ActiveRecord::Base | |
has_and_belongs_to_many :cars | |
scope :paid, -> { where(paid: true) } | |
# get people who have paid and have | |
# cars with fuel | |
# | |
# SELECT "people".* | |
# FROM "people" | |
# INNER JOIN "cars_people" ON "cars_people"."person_id" = "people"."id" | |
# INNER JOIN "cars" ON "cars"."id" = "cars_people"."car_id" | |
# WHERE "people"."paid" = 't' AND "cars"."fueled" = 't' | |
def self.good_to_go | |
paid.joins(:cars).merge(Car.fueled) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment