Skip to content

Instantly share code, notes, and snippets.

@kulbida
Forked from ngauthier/merge.rb
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kulbida/07e8c6cc6996066ac0d5 to your computer and use it in GitHub Desktop.
Save kulbida/07e8c6cc6996066ac0d5 to your computer and use it in GitHub Desktop.
# 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