2011-05-01 114 views
0

你好 我是新的RoR。如何將簡單的控制器邏輯切換到模型? 我的數據庫列是ORDER_TYPE,數量,quantity_adjusted從控制器移動代碼到模型(薄控制器胖模型)

控制器

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 

感謝 LH

回答

1

有很多方法可以做到這一點。一種可能的最自然的方式是創建一個實例方法,如:

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