我的模型设置如下:
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方法是什么才能使联接表范围在关联之间工作而无需指定它?是否存在?
答案 0 :(得分:10)
在#ruby-on-rails的dfr的帮助下找出答案。
在User类中,将has_many关系设置为:
has_many :words, :through => :items, :conditions => { "items.active" => true }
这是因为尽管User和Word之间存在habtm连接关联,但在调用user.words时实际上并未加载Item模型。因此,您必须在用户模型中的关联上应用范围。
希望有人帮助过。
答案 1 :(得分:2)
谢谢你的帮助。此票证(虽然无效)也让人们讨论它:https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3610-has_many-through-associations-may-not-respect-default_scope-conditions#ticket-3610-17
就个人而言,我觉得这张票并非无效。默认范围是默认范围。