ruby Rails包含不同的值

vddsk6oq  于 2023-10-17  发布在  Ruby
关注(0)|答案(1)|浏览(83)

我有一个标准的ruby includes,smth。就像这样

@properties = Property.where(id: property_ids)
    .includes(:property_values).select('select distinct "property_values"."value"').references(:property_values)

我需要每个属性值的uniq值。
但是对于这个查询得到一个错误:

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属性值?

9udxz4iz

9udxz4iz1#

@properties = Property.where(id: property_ids).
  joins(:property_values).
  select('"property_values"."value"').
  distinct.
  references(:property_values)

注意,我将includes更改为join,因为includes在单独的查询中加载数据,而join实际上执行join,允许您对查询中的数据执行操作。
我使用了distinct方法,而不是将其放在select中,但是您可以这样做,但您需要从字符串中删除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

相关问题