レールには個別の値が含まれます
概要
私は標準の Ruby インクルードを持っています。そのように:
@properties = Property.where(id: property_ids)
.includes(:property_values).select('select distinct "property_values"."value"').references(:property_values)
各プロパティのプロパティ値に一意の値が必要です。
しかし、このクエリではエラーが発生します。
PG::SyntaxError - ERROR: syntax error at or near "select"
LINE 1: ...S t1_r4, "property_values"."updated_at" AS t1_r5, select dis...
完全なクエリは次のとおりです。
: SELECT "properties"."id" AS t0_r0, "properties"."k1c" AS t0_r1, "properties"."name" AS t0_r2, "properties"."created_at" AS t0_r3, "properties"."updated_at" AS t0_r4, "property_values"."id" AS t1_r0, "property_values"."value" AS t1_r1, "property_values"."product_id" AS t1_r2, "property_values"."property_id" AS t1_r3, "property_values"."created_at" AS t1_r4, "property_values"."updated_at" AS t1_r5, select distinct "property_values"."value" FROM "properties" LEFT OUTER JOIN "property_values" ON "property_values"."property_id" = "properties"."id" WHERE "properties"."id" IN (159, 27, 26, 25, 24, 23, 22, 4, 1) AND "properties"."id" IN (1) ORDER BY "properties"."id" ASC
このエラーを回避して、uniq プロパティ値のみを取得するにはどうすればよいですか?
解決策
@properties = Property.where(id: property_ids).
joins(:property_values).
select('"property_values"."value"').
distinct.
references(:property_values)
include は別のクエリでデータをロードするため、include を join に変更しましたが、join は実際に結合を実行するので、クエリ内のデータに対してアクションを実行できることに注意してください。
select内に置く代わりにdistinctメソッドを使用しましたが、これを行うこともできますが、文字列からselectという単語を削除する必要があります
@properties = Property.where(id: property_ids)
joins(:property_values).
select('distinct "property_values"."value"').
references(:property_values)
続きを読む http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html