开发者

ActiveRecord combining relations

开发者 https://www.devze.com 2023-04-08 12:15 出处:网络
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 i

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消