使用 has_many 重新创建此自定义查询
我希望这将是一个简单的:)我已经花了几个小时玩 has_many 选项试图模拟这一点:
has_many :pages, :finder_sql => %q(SELECT * FROM `pages` LEFT OUTER JOIN `component_instances` ON `component_instances`.instance_id = `pages`.id AND `component_instances`.instance_type = 'Page' WHERE `component_instances`.parent_id = #{id})
它基本上是一个多态连接,所以有一个 component_instances 表充当中心结构并具有不同的功能挂在上面的东西类型。 这是一个嵌套集(在本例中这并不重要)。
问题似乎是 has_many 不允许我操纵连接条件。 而且我无法取消自动创建的外键连接条件。
上面的代码有效,但我想在结果上使用范围,而这对于自定义查询是不可能的。
任何帮助将不胜感激:)
干杯,
布伦登
I'm hoping this will be an easy one :) I've been stuffing around for hours playing with the has_many options trying to emulate this:
has_many :pages, :finder_sql => %q(SELECT * FROM `pages` LEFT OUTER JOIN `component_instances` ON `component_instances`.instance_id = `pages`.id AND `component_instances`.instance_type = 'Page' WHERE `component_instances`.parent_id = #{id})
It's basically a polymorphic join so there is the component_instances table that acts as a central structure and has different types of things hanging off of it. It's a nested set (not that that matters in this case).
The problem seems to be that has_many doesn't allow me to manipulate the join conditions. And I can't nullify the foreign key join condition that's automatically made.
The above code works but I want to use scopes on the results, and that's not possible with a custom query.
Any help would be greatly appreciated :)
Cheers,
Brendon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 :through 选项来执行此操作。
You can do this with the :through option.
感谢迈克尔的领导,最终这成功了:
但它有点粗略,因为 :page_set 方法实际上返回了完全错误的东西。 理想情况下它应该返回 self,但我需要将 :parent_id 作为外键,以便从 has_many 页面声明生成的 SQL 是正确的(使用 :id 是正确的方法,但随后会搞砸 :pages 方法。:) 我的头脑还没有完全弄清楚这里发生了什么,但至少它有效并且范围界定也有效:)
感谢您的帮助,如果您对为什么有效有任何解释,请告诉我:)
Thanks for the lead Michael, in the end this worked:
but it's a little bit sketchy as the :page_set method actually returns something completely wrong. Ideally it should return self but I needed to put :parent_id as the foreign key so that the SQL generated from the has_many pages declaration was correct (using :id would be the correct way but then that screws up the :pages method. :) My mind hasn't quite gotten around what's going on here, but at least it works and scoping works too :)
Thanks for the help, and if you have any explanations as to why that works, please let me know :)
哈哈,睡在上面给了我答案:
通过 Parent_id 链接的实体是正确的子实体,我只是以错误的方式引用它们,但 AR 没有引发任何错误:)
Lol, sleeping on it gave me the answer:
The entities with the link through parent_id are rightly children, I was just referring to them in the wrong way, but AR didn't raise any errors :)