Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ngauthier
Created June 25, 2014 14:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ngauthier/372f504a83f269c5c727 to your computer and use it in GitHub Desktop.
Save ngauthier/372f504a83f269c5c727 to your computer and use it in GitHub Desktop.
ActiveRecord Scope Merging
# 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