Skip to content

Instantly share code, notes, and snippets.

View Breefield's full-sized avatar

Bree Hoffman Breefield

View GitHub Profile
class Event < ActiveRecord::Base
has_one :location, as: :located, dependent: :destroy
accepts_nested_attributes_for :location
end
Event.create(name: 'Coffee Party', location_attributes: {address: '3126 16th St. San Francisco, CA 94103'})
# (0.2ms) begin transaction
# SQL (2.8ms) INSERT INTO "events" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Fri, 22 Nov 2013 19:09:51 UTC +00:00], ["name", "Coffee Party"], ["updated_at", Fri, 22 Nov 2013 19:09:51 UTC +00:00]]
# SQL (0.3ms) INSERT INTO "locations" ("address", "created_at", "latitude", "located_id", "located_type", "longitude", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["address", "3126 16th St. San Francisco, CA 94103"], ["created_at", Fri, 22 Nov 2013 19:09:51 UTC +00:00], ["latitude", 37.7648968], ["located_id", 2], ["located_type", "Event"], ["longitude", -122.4225344], ["updated_at", Fri, 22 Nov 2013 19:09:51 UTC +00:00]]
# (2.2ms) commit transaction
# <Event id: 2, name: "Coffee Party", created_at: "2013-11-22 19:09:51", updated_at: "2013-11-22 19:09:51">
class Location < ActiveRecord::Base
belongs_to :located, :polymorphic => true
geocoded_by :address
before_validation :geocode, :if => :changed?
end
Location.near('San Francisco', 50).each { |location| puts location.located }
Location.near('San Francisco', 50).each { |location| puts location.located }
@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)
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)
.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')
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')