Question

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 all 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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top