Skip to content

Instantly share code, notes, and snippets.

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