2011-05-01 3 views
0

안녕하세요 저는 RoR을 신설했습니다. 어떻게 간단한 컨트롤러 로직을 모델로 전환 할 수 있습니까? 내 데이터베이스 열 ORDER_TYPE, 수량,컨트롤러에서 모델로 코드 이동 (씬 컨트롤러 지방 모델)

컨트롤러

def create 

@product = Product.new(params[:product]) 

# This is the control structure I want to move to Model 

if @product.order_type = "Purchase" 
    @product.quantity_adjusted = -quantity 
else 
    @product.quantity_adjusted = quantity 
end 

end 

모델

class Product < ActiveRecord::Base 
end 

감사를 할 수있는 여러 가지 방법이 있습니다

답변

1

LH quantity_adjusted. 가장 자연스러운 방법 중 하나는 제품 모델에

def adjust_quantity(amount) 
    (put logic here) 
end 

과 같은 인스턴스 메서드를 만드는 것입니다. 그런 다음 컨트롤러에서 다음을 수행합니다.

@product.adjust_quantity(quantity) 
0

모델에서 콜백을 사용할 수 있습니다. 예 : after_create.

컨트롤러 :

def create 
    @product = Product.new(params[:product]) 

    if @product.save 
    # redirect 
    else 
    render :new 
    end 
end 

모델 :

class Product < ActiveRecord::Base 
    after_create :adjust_quantity 

    private 

    def adjust_quantity 
    if self.order_type == "Purchase" 
     self.quantity_adjusted = -quantity 
    else 
     self.quantity_adjusted = quantity 
    end 
    end 
end 
관련 문제