Default_scope on the connection table

I have a model setup, for example:

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 encountered is that default_scope does not apply to the following association:

  user.words 

SQL instead:

 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 believe this is because the default scope works for the regular model and its child association, but not for join tables.

What is the right way for Rails to get the join table area for collaboration between associations without having to specify it? Does it exist?

+6
scope ruby-on-rails default-scope has-and-belongs-to-many has-many-through
source share
2 answers

Find out the answer using dfr from # ruby-on-rails.

In the User class, set the has_many relation as follows:

  has_many :words, :through => :items, :conditions => { "items.active" => true } 

This is because although there is an association association between the user and Word, the Item model does not actually load when user.words is called. Therefore, you must apply the scope to the association in the user model.

Hope someone helped.

+10
source share

Thanks, this is helpful. There are people on this ticket (albeit invalid) who discuss it: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3610-has_many-through-associations-may-not-respect -default_scope-conditions # ticket-3610-17

Personally, I feel that this ticket is NOT MALFUNCTIVE. The default value is the default area.

+2
source share

All Articles