Set value in controller using nested resource
I have two models, product and order.
Product
- cost
- id
Order
- cost
- product_id
Each time someone places an order, it captures the product_id through a radio button value in the "new order" form.
In the controller when creating the new order it needs to set order.cost to order.product.cost. Logically I thought the code should be something like this:
def create
...
@order.cost == @order.produc开发者_运维知识库t.cost
...
end
However I can't seem to make it work at all, hence me asking the question here.
Any help is answering (or naming) the question would be greatly appreciated.
Wrong syntax
@order.cost == @order.product.cost #it will compare the product cost & order cost & return boolean value true ot false
Its should be
@order.cost = @order.product.cost
Assuming you write associations properly in model it should be as follows
product.rb
has_many :orders
order.rb
belongs_to :product
Another option would be specifying a before_create on the Order model, but this would only work if EVERY Order needs to be created in this way.
class Order < ActiveRecord::Base
has_many :products
#this could be has_one if you really want only one product per order
accepts_nested_attributes_for :products
#so that you can do Order.new(params[:order])
#where params[:order] => [{:attributes_for_product => {:id => ...}}]
#which is handled by fields_for in the view layer.
#has_one would make this :product
before_create :calculate_order_cost_from_product
#only run on the first #save call or on #create
def calculate_order_cost_from_product
self.cost = self.products.first.cost
#this could also be self.products.sum(&:cost)
#if you wanted the total cost of all the products
#has_one would be as you had it before:
#self.cost = self.product.cost
end
end
精彩评论