开发者

Virtual columns in a model

开发者 https://www.devze.com 2023-01-28 14:08 出处:网络
Is it possible to add a virtual column to a model (not virtual attribute!)? I have following situation:

Is it possible to add a virtual column to a model (not virtual attribute!)?

I have following situation: A Product(id, name) has many ProductVariant(id, price, offer_price, product_id,...)

When I select al开发者_如何学Pythonl products I want to have the minimum product price from all ProductVariants in the products result.

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

I calculate the minimum price in a sql query (with_min_price) and want to add this min_price value to each Product in my @products result.


This could just be a method in your Product class assuming your Product has_many ProductVarients

#Product Model

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


You can do this with a custom select, though the column will be read-only:

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

You can also use the new column as you would a calculated column in SQL in any of the other parts of a find or the Rails 3 equivalents.

0

精彩评论

暂无评论...
验证码 换一张
取 消