2010-04-12 108 views
0

我有兩個模型,產品和訂單。使用嵌套資源的控制器中的設置值

Product 
- cost 
- id 

Order 
- cost 
- product_id 

每次有人下訂單,它通過在「新秩序」形式的單選按鈕值捕捉PRODUCT_ID。

在控制器創建新訂單時,需要將order.cost設置爲order.product.cost。按道理我認爲代碼應該是這樣的:

def create 
... 
    @order.cost == @order.product.cost 
... 
end 

但是我似乎無法使它在所有的工作,因此我問這個問題在這裏。

任何幫助回答(或命名)的問題將不勝感激。

回答

0

語法錯誤

@order.cost == @order.product.cost #it will compare the product cost & order cost & return boolean value true ot false 

它應該是

@order.cost = @order.product.cost 

假設你寫協會正確模型應該是如下

product.rb

has_many :orders 

或der.rb

belongs_to :product 
0

另一個選擇是指定的訂單模型before_create,但如果每一個訂單需要以這種方式來創建這個只會工作。

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 
相關問題