连接表上的 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
我遇到的问题是 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方法是什么?有吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 #ruby-on-rails 的 dfr 的帮助下找到了答案。
在User类中,将has_many关系设置为:
这是因为虽然User和Word之间存在habtm join关联,但是在调用user.words时并没有真正加载Item模型。因此,您必须将范围应用于用户模型内的关联。
希望对某人有帮助。
Figured out the answer with the help of dfr from #ruby-on-rails.
In the User class, set the has_many relation to be:
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.
谢谢,它很有帮助。这张票(尽管无效)也引起了人们的讨论:https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3610-has_many-through-associations- may-not-respect-default_scope-conditions#ticket-3610-17
就我个人而言,我觉得这张票不是无效的。默认范围是默认范围。
Thanks it is helpful. This ticket (though invalid) has people discussing it as well: 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 like this ticket is NOT invalid. Default Scope is Default Scope.