2

是否可以向模型添加虚拟列(不是虚拟属性!)?

我有以下情况:AProduct(id, name)有很多ProductVariant(id, price, offer_price, product_id,...)

当我选择所有产品时,我希望从ProductVariants产品结果中的所有产品中获得最低产品价格。

@products = Product.with_min_price.order('min_price ASC')

我在 sql 查询 () 中计算最低价格,with_min_price并希望将此min_price值添加到Product我的@products result.

4

2 回答 2

4

假设您的 Product has_many ProductVarients 这可能只是您的 Product 类中的一个方法

#Product Model

def min_product_price
  product_variants.map(&:price).min
end
于 2010-12-01T17:17:30.760 回答
2

您可以使用自定义选择来执行此操作,尽管该列将是只读的:

>> order = Order.find(:first, :select => "(id+111) as order_number")
=> #<Order order_number: "119"
>> order.order_number
=> "119"

您还可以在 find 的任何其他部分或 Rails 3 等效项中使用新列,就像使用 SQL 中的计算列一样。

于 2010-12-01T17:24:33.323 回答