Created
June 11, 2013 14:45
-
-
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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