7

我有一个如下模型设置:

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

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

 user.words

而不是这个 SQL:

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

我在日志中得到这个 SQL:

SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) 

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

什么是让连接表范围在关联之间工作而无需指定的正确 Rails 方法?一个存在吗?

4

2 回答 2

11

在#ruby-on-rails 的dfr 的帮助下找到了答案。

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

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

这是因为虽然 User 和 Word 之间存在 habtm join 关联,但调用 user.words 时并未实际加载 Item 模型。因此,您必须将范围应用于 User 模型中的关联。

希望对某人有所帮助。

于 2011-03-28T18:50:38.237 回答
2

谢谢,它很有帮助。这张票(虽然无效)也有人在讨论它:https ://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3610-has_many-through-associations-may-not-respect-default_scope -条件#ticket-3610-17

就个人而言,我觉得这张票不是无效的。默认范围是默认范围。

于 2011-03-29T14:32:37.123 回答