Skip to content

Instantly share code, notes, and snippets.

@libbyschuknight
Last active November 23, 2018 03:27
Show Gist options
  • Save libbyschuknight/8db9a042d497695ab5647ac2137dbde3 to your computer and use it in GitHub Desktop.
Save libbyschuknight/8db9a042d497695ab5647ac2137dbde3 to your computer and use it in GitHub Desktop.
describe Location do
describe ".in_region" do
it "returns locations in the named region" do
region = create(:region, name: "expected")
other_region = create(:region, name: "other")
create(:location, region: region, name: "in-expected-region-one")
create(:location, region: region, name: "in-expected-region-two")
create(:location, region: other_region, name: "in-other-region")
result = Location.in_region("expected")
expect(result.map(&:name)).
to match_array(%w(in-expected-region-one in-expected-region-two))
end
end
end
#==== SOLUTION ====#
# 1st iteration
class Location < ActiveRecord::Base
belongs_to :region
has_many :people
def self.in_region(region)
all.select { |location| location.region.name == region }
end
end
# 2nd iteration
def self.in_region(region)
all.joins(:region).where(regions: { name: region })
end
# sql
Location.all.joins(:region).where(regions: { name: region })
SELECT "locations".*
FROM "locations"
INNER JOIN "regions"
ON "regions"."id" = "locations"."region_id"
WHERE "regions"."name" = 'expected'
# 3rd
class Region < ActiveRecord::Base
has_many :locations
def self.in_region(region)
where(name: region)
end
end
Location.all.joins(:region).merge(Region.in_region(region)).to_sql
SELECT "locations".*
FROM "locations"
INNER JOIN "regions"
ON "regions"."id" = "locations"."region_id"
WHERE "regions"."name" = 'expected'
# final
class Location < ActiveRecord::Base
belongs_to :region
has_many :people
def self.in_region(region)
joins(:region).merge(Region.in_region(region))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment