2011-05-01 175 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