Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default_scope on a join table

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?

like image 873
joeellis Avatar asked Mar 28 '11 18:03

joeellis


1 Answers

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.

like image 178
joeellis Avatar answered Sep 20 '22 05:09

joeellis