Skip to content

Instantly share code, notes, and snippets.

@peterklipfel
Last active December 30, 2015 20:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterklipfel/7884798 to your computer and use it in GitHub Desktop.
Save peterklipfel/7884798 to your computer and use it in GitHub Desktop.
nested scopes bug
class Bike < ActiveRecord::Base
belongs_to :person
has_many :wheels
scope :all_for_city, -> (city_id) { Bike.joins(:person).load.merge Person.all_for_city(city_id) }
end
rails new nested_scope_bug
cd nested_scope_bug
rails g model city name:string
rails g model person name:string city:references
rails g model bike color:string person:references
rails g model wheel size:decimal bike:references
rails g model spokes material:string wheel:references
rm app/models/city.rb
rm app/models/person.rb
rm app/models/bike.rb
rm app/models/wheel.rb
rm app/models/spoke.rb
echo "class City < ActiveRecord::Base
has_many :people
end" >> app/models/city.rb
echo "class Person < ActiveRecord::Base
belongs_to :city
has_many :bikes
scope :all_for_city, -> (city_id) { where(city_id: city_id) }
end" >> app/models/person.rb
echo "class Bike < ActiveRecord::Base
belongs_to :person
has_many :wheels
scope :all_for_city, -> (city_id) { Bike.joins(:person).load.merge Person.all_for_city(city_id) }
end" >> app/models/bike.rb
echo "class Wheel < ActiveRecord::Base
belongs_to :bike
has_many :spokes
scope :all_for_city, -> (city_id) { Wheel.joins(:bike).load.merge Bike.all_for_city(city_id) }
end" >> app/models/wheel.rb
echo "class Spoke < ActiveRecord::Base
belongs_to :wheel
scope :all_for_city, -> (city_id) { Spoke.joins(:wheel).load.merge Bike.all_for_city(city_id) }
end" >> app/models/spoke.rb
rake db:migrate
echo "City.create(name: 'Boulder')" | rails c
echo "Spoke.all_for_city(City.first.id)" | rails c
echo "Person.all_for_city(City.first.id)" | rails c
echo "Bike.all_for_city(City.first.id)" | rails c
echo "Wheel.all_for_city(City.first.id)" | rails c
echo "Spoke.all_for_city(City.first.id)" | rails c
class Person < ActiveRecord::Base
belongs_to :city
has_many :bikes
scope :all_for_city, -> (city_id) { where(city_id: city_id) }
end
class Spoke < ActiveRecord::Base
belongs_to :wheel
scope :all_for_city, -> (city_id) { Spoke.joins(:wheel).load.merge Bike.all_for_city(city_id) }
end
class Wheel < ActiveRecord::Base
belongs_to :bike
has_many :spokes
scope :all_for_city, -> (city_id) { Wheel.joins(:bike).load.merge Bike.all_for_city(city_id) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment