所以我试图将2个ActiveRecord :: relation结果合并为1(基本上是一个OR类型的操作)。由于Rails 4无意将此作为一项功能,我转向Arel。您可以从下面的代码中看到它没有将两种关系组合到正确的sql查询中。我如何做到这一点,以便我最终得到一个SQL查询,以便我在合并语句中有“kites.flying_status = Flying”而不是“kites.flying_status = UNION SELECT ...”?
@kites = Kite.search_kites("red").by_flying_status("Flying)")
kites.to_sql的SQL结果
"SELECT \"kites\".* FROM \"kites\" WHERE \"kites\".\"id\" IN (336, 334, 176, 238, 335, 162, 439, 385, 158, 276, 379, 378, 310, 391, 416, 342, 281) AND \"kites\".\"flying_status\" = 'Flying'"
Kite.where的SQL结果(id:locs.pluck(:kite_id))。to_sql
"SELECT \"kites\".* FROM \"kites\" WHERE \"kites\".\"id\" IN (162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 162, 162, 238, 238, 238)"
组合两个activerecord关系的代码:
arel_union_trials = @kites.union(Kite.where(id: locs.pluck(:kite_id)))
kite_arel_table = Kite.arel_table
@kites = Kite.from(kite_arel_table.create_table_alias(arel_union_trials, :kites)).distinct
@ kites.union(Kite.where(id:locs.pluck(:kite_id)))。to_sql结果:
SELECT "kites".* FROM ( SELECT "kites".* FROM "kites" WHERE "kites"."id" IN (336, 334, 176, 238, 335, 162, 439, 385, 158, 276, 379, 378, 310, 391, 416, 342, 281) AND "kites"."flying_status" = UNION SELECT "kites".* FROM "kites" WHERE "kites"."id" IN (162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 162, 162, 238, 238, 238) ) "kites"
E, [2015-02-27T12:48:12.941237 #7408] ERROR -- : PG::SyntaxError: ERROR: syntax error at or near "UNION"
LINE 1: ...281) AND "kites"."flying_status" = UNION SELE...
^
: SELECT "kites".* FROM ( SELECT "kites".* FROM "kites" WHERE "kites"."id" IN (336, 334, 176, 238, 335, 162, 439, 385, 158, 276, 379, 378, 310, 391, 416, 342, 281) AND "kites"."flying_status" = UNION SELECT "kites".* FROM "kites" WHERE "kites"."id" IN (162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 162, 162, 238, 238, 238) ) "kites"