2010-12-01 93 views
2

是否可以将虚拟列添加到模型(不是虚拟属性!)?模型中的虚拟列

我有以下情况: 一个Product(id, name)有许多ProductVariant(id, price, offer_price, product_id,...)

当我选择我想要从产品结果所有ProductVariants最低产品价格的所有产品。

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

我计算出的最低价格在一个SQL查询(with_min_price),并希望在我@products result添加此min_price值每Product

回答

4

这可能只是你的产品类中的方法假设你的产品的has_many ProductVarients

#Product Model 

def min_product_price 
    product_variants.map(&:price).min 
end 
+0

如果它是一个类方法,那应该是`def self.min_product_price`吗? – 2010-12-01 17:26:01

+0

哎呀,是的,那不是类方法,它是对象上的方法。我更新了答案。你只需要调用`@ products.each {| p | p.min_product_price}` – brycemcd 2010-12-01 21:54:19

2

您可以用自定义选择这样做,虽然列将是只读的:

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

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