Rails:链接作用域时可以合并连接吗?
在类 AI 中,有两个作用域,s1 和 s2,它们都使用完全相同的连接列连接表 T:
named_scope :s1 :joins => "JOIN T on T.id = A.t_id", ...some conditions
named_scope :s2 :joins => "JOIN T on T.id = A.t_id", ...some other conditions
现在,这样做会失败:
A.s1.s2.all
错误:
ActiveRecord::StatementInvalid: Mysql::Error: 不唯一的表/别名:'T'
我有点期望 Rails 对这些相同的连接很聪明,并且只需应用一次连接,但事实并非如此。我可以使用表别名,但是我仍然会无缘无故地有两个相同的连接。
我确信一定有一个适当的解决方案吗?
In a class A I have two scopes, s1 and s2 which both join over a table T using the exact same join columns:
named_scope :s1 :joins => "JOIN T on T.id = A.t_id", ...some conditions
named_scope :s2 :joins => "JOIN T on T.id = A.t_id", ...some other conditions
Now, doing this fails:
A.s1.s2.all
Error:
ActiveRecord::StatementInvalid: Mysql::Error: Not unique table/alias: 'T'
I sort of expected Rails to be smart about those identical joins, and simply apply the join once, but it doesn't. I could use table aliases, but then I'd still have two identical joins for no good reason.
I'm sure there must be a proper solution to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,这是 Rails 2.3.4 中的一个错误:
在我的实际代码中,我在 JOIN 表达式中对 ON 关键字使用了不同的字符大小写,而 Rails 不够智能,无法合并它。显然,作用域对 JOIN 字符串进行区分大小写的比较。
我打开了一个错误报告: 链接文本
Turned out this is a bug in Rails 2.3.4:
In my actual code I used different character case for the ON keyword in the JOIN expression, and Rails wasn't smart enough to merge that. Apparently scopes do case sensitive comparison on JOIN strings.
I opened a bug report: link text