2010-04-12 2 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 

또는 또 다른 옵션은 주문 모델에 before_create를 지정하는 것입니다, 그러나 모든 주문이 방법으로 생성 할 필요가있을 경우에만 동작 것

belongs_to :product 
0

der.rb.

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 
관련 문제