【发布时间】:2012-03-04 21:19:22
【问题描述】:
我有两个模型
class Product < ActiveRecord::Base
belongs_to :category
end
class Product < ActiveRecord::Base
belongs_to :category
end
现在我想列出所有类别及其最便宜的产品。通过获取所有类别,迭代它们并单独查找最便宜的产品,这很容易完成,但这会进行大量查询并且非常慢。我可以用 sql 很容易地做到这一点——比如
SELECT products.*, categories.*
FROM products
JOIN categories ON (categories.id = products.owner_id)
LEFT JOIN products as cheaper_products ON
cheaper_products.category_id = epochs.category_id AND
cheaper_products.price < products.price
WHERE cheaper_products.owner_id IS NULL
这是一个很好的 SQL 技巧,我们将类别内的所有更便宜的产品“左连接”到每个产品,而不是只选择那些没有任何产品的产品。
我想知道如何使用 Rails3 关系来完成类似的事情 - 我正在使用 squeel,所以它也可以使用。
观察:我想过在 Products 上定义一个关系 :cheaper_products,但似乎也无济于事。
另一个想法:也可以通过返回其类别中所有最便宜产品的 id 的子查询来解决它,但它也没有让我解决(而且不太优雅)。
注意:我知道如何使用 bruteforce (selector_sql) 来做到这一点,但我真的很想了解更多 rails 3 方法。
【问题讨论】:
-
我知道它不完全符合您的要求,但您可以在数据库中创建索引。看看postgresql.org/docs/current/static/indexes-expressional.html
标签: sql ruby-on-rails-3 scope associations arel