如何正确地将此SQL转换为ActiveRecord?

时间:2013-07-08 15:28:53

标签: ruby-on-rails activerecord

我想选择属于某个产品的items。它们必须在items.condition上区别开来。这是查询:

SELECT DISTINCT ON (items.condition) items.id, items.condition, items.price, products.name
FROM products
INNER JOIN items ON products.id = items.product_id
WHERE products.id = 1
ORDER BY items.condition, items.price, products.name;

我尝试了这个,但我收到StatementInvalid错误。我正在使用Rails 4。

product = Product.find(1)
product.items.select("DISTINCT ON(items.condition) items.id, products.*, items.*").order('items.condition, items.price, products.name')

错误:

PG::Error: ERROR:  missing FROM-clause entry for table "products"
LINE 1: SELECT DISTINCT ON(items.condition) items.id, products.*, it...
                                                      ^
: SELECT DISTINCT ON(items.condition) items.id, products.*, items.* FROM "items"  WHERE "items"."product_id" = $1  ORDER BY items.condition, items.price, products.name
ActiveRecord::StatementInvalid: PG::Error: ERROR:  missing FROM-clause entry for table "products"
LINE 1: SELECT DISTINCT ON(items.condition) items.id, products.*, it...

1 个答案:

答案 0 :(得分:2)

试试这个(未经测试)

Product.joins(:items).select("DISTINCT(items.condition), items.id, products.*").order('items.condition, items.price, products.name')