Skip to content

Instantly share code, notes, and snippets.

@nathanl
Created June 11, 2013 14:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nathanl/5757443 to your computer and use it in GitHub Desktop.
Save nathanl/5757443 to your computer and use it in GitHub Desktop.
Using joins and conditions in ActiveRecord scopes. (This was hard for me to find documentation on.)
class Person < ActiveRecord::Base
# This manual SQL query...
scope :allowed_to_eat_cheese, joins(
<<-SQL
INNER JOIN cities ON people.city_id = cities.id
INNER JOIN states ON cities.state_id = states.id
SQL
).where('states.allows_cheese_consumption' = 'Yeppers')
# ... can be automated by this ActiveRecord syntax
scope :allowed_to_eat_cheese,
joins: {:city => [:state]}, conditions: {'states.allows_cheese_consumption' => 'Yeppers' }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment