I've got a model setup like the following:
class User
has_many :items
has_many :words, :through => :items
end
class Item
belongs_to :user
belongs_to :word
default_scope where(:active => true)
end
class Words
has_many :items
end
The problem I'm having is that the default_scope is not being applied to the following association:
user.words
Instead of this SQL:
SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) AND ((`items.active = 1))
I get this SQL in the logs:
SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1))
I figure this is because the default scope works for a regular model and its child association, but not for join tables.
What is the correct Rails way to get a join table scope to work between associations without needing to specify it? Does one exist?
Figured out the answer with the help of dfr from #ruby-on-rails.
In the User class, set the has_many relation to be:
has_many :words, :through => :items, :conditions => { "items.active" => true }
This is because although there is a habtm join association between User and Word, the Item model is not actually loaded when user.words is called. Therefore you have to apply the scope on the association within the User model.
Hope that helped someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With