连接表上的Default_scope

joe*_*lis 6 scope ruby-on-rails has-and-belongs-to-many has-many-through default-scope

我有一个如下模型设置:

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
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是default_scope没有应用于以下关联:

 user.words
Run Code Online (Sandbox Code Playgroud)

而不是这个SQL:

SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) AND ((`items.active = 1))
Run Code Online (Sandbox Code Playgroud)

我在日志中得到这个SQL:

SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) 
Run Code Online (Sandbox Code Playgroud)

我认为这是因为默认范围适用于常规模型及其子关联,但不适用于连接表.

使连接表范围在关联之间工作而不需要指定它的正确Rails方法是什么?有人存在吗?

joe*_*lis 10

在#ruby-on-rails的dfr的帮助下找出了答案.

在User类中,将has_many关系设置为:

 has_many :words, :through => :items, :conditions => { "items.active" => true }
Run Code Online (Sandbox Code Playgroud)

这是因为尽管User和Word之间存在habtm连接关联,但在调用user.words时实际上并未加载Item模型.因此,您必须在User模型中的关联上应用范围.

希望有人帮助过.