Skip to content

Instantly share code, notes, and snippets.

View Breefield's full-sized avatar

Bree Hoffman Breefield

View GitHub Profile
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start
require 'rspec/rails'
require 'rspec/autorun'
Location.near('San Francisco', 50).filtered_by(:event).where('events.price <= ?', 20)
# Type is a :symbol of the model which you want to filter by
def self.filtered_by type
belongs_to type, :foreign_key => :located_id, :foreign_type => type.to_s.capitalize
where(:located_type => type.to_s.capitalize).joins(type).includes(:located)
end
Location.near('San Francisco', 50)
.where(located_type: 'Event') # Filter other polymorphic models out
.joins(:event) # ...JOIN events ON...
.where('events.price <= ?', 20) # Filter events by their price
.includes(:event) # Avoid N+1
.reorder('events.price ASC, distance ASC')
reorder('events.price ASC, distance ASC')
@Breefield
Breefield / near.rb
Last active December 29, 2015 03:09
Location.near('San Francisco', 50)
.where(located_type: 'Event') # Filter other polymorphic models out
.joins(:event) # ...JOIN events ON...
.where('events.price <= ?', 20) # Filter events by their price
.includes(:event) # Avoid N+1
class Location < ActiveRecord::Base
# ...
belongs_to :event, :foreign_key => :located_id, :foreign_type => 'Event'
# ...
end
@Breefield
Breefield / near.rb
Last active December 29, 2015 03:09
Location.near('San Francisco', 50)
.includes(:owner)
# Event Load (0.2ms) SELECT "events".* FROM "events" WHERE "events"."id" IN (3, 1, 2)
# Venue Load (0.3ms) SELECT "venues".* FROM "venues" WHERE "venues"."id" IN (1, 2, 3)
Location.near('San Francisco', 50).each { |location| puts location.located }
Location.near('San Francisco', 50).each { |location| puts location.located }