Intersection of two relations

前端 未结 5 2105
情歌与酒
情歌与酒 2020-12-16 17:06

Say I have two relations that hold records in the same model, such as:

@companies1 = Company.where(...)
@companies2 = Company.where(...)

Ho

5条回答
  •  青春惊慌失措
    2020-12-16 17:14

    I solve similar problem this way

    Company.connection.unprepared_statement do
      Company.find_by_sql "#{@companies1.to_sql} INTERSECT #{@companies2.to_sql}"
    end
    

    We need unprepared_statement block here because latest Rails versions use prepared statements to speed up arel queries, but we need pure SQL in place.

提交回复
热议问题