ActiveRecord组合关系
我想知道是否有更好的方法来做到这一点:
我有 2 个复杂的关系,其中多个连接连接到表 D。我想组合/连接它们以获得表 D 记录。以下方法可行,但有更好的方法吗?
class TableD < ActiveRecord::Base
def self.relation_three
r1 = TableA.relation_one.select("d.id")
r2 = TableB.relation_two.select("d.id")
where("d.id IN (#{r1.to_sql}) OR d.id IN (#{r2.to_sql})")
end
如果这是不可能的,那么我有一个补充问题:
是否可以返回与查询所基于的记录不同的活动记录结果类?即:
TableA.all.joins(:b).select("b.*") # Coerce into TableB class ?
谢谢!
I'm wondering if there's a nicer way to do this:
I have 2 complex relations with multiple joins joining to Table D. I want to combine/join them to get the Table D records. The following works but is there a better way?
class TableD < ActiveRecord::Base
def self.relation_three
r1 = TableA.relation_one.select("d.id")
r2 = TableB.relation_two.select("d.id")
where("d.id IN (#{r1.to_sql}) OR d.id IN (#{r2.to_sql})")
end
And if that's not possible then I have a supplementary question:
Is it possible to return an active record result class different from the record the query is based on? ie:
TableA.all.joins(:b).select("b.*") # Coerce into TableB class ?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论