2009-10-12 18 views
0

我试图使属性等于预定值,而且我不确定是否可以高效地使用以下(在我的订单控制器中) :Ruby on Rails:在控制器(或可能是模型)中等价物品

def create 
    @order = Order.find(params[:id]) 
    @order.price = 5.99 
    @order.representative = Product.find(params[:product_id]).representative 
    @order.shipping_location = SHIPPING_LOCATION 
    @order.user = current_user 

    respond_to do |format| 
    ... 
    end 
end 

有没有一种更有效的方法来在Rails(也许使用模型)中等同属性?如果我使用两个不同的控制器,是否重复上面为新控制器所做的操作?

回答

3

在模型中使用before_create回调来分配默认值。

3

你的代码有点不对,它看起来像是一个控制器为创建操作,但代码读取像它的更新。

无论如何... 您可以使用参数散列一次更新所有内容。

的情况下,你要创建:

order_update = {:price => 5.99, :representative => 
    Product.find(params[:product_id]).representative, 
    :shipping_location => SHIPPING_LOCATION, 
    :user => current_user} 

@order = Order.new(order_update) 

在这种情况下,你要更新:

@order.update_attributes(order_update) #attempts to save. 

混合到你的控制器代码,我们得到:

def create 
    @order = Order.find(params[:id]) 
    order_update = {:price => 5.99, :representative => 
    Product.find(params[:product_id]).representative, 
    :shipping_location => SHIPPING_LOCATION, 
    :user => current_user}  

    respond_to do |format| 
    if @order.update_attributes(order_update) 
     # save succeeded. Redirect. 
    else 
     # save failed. Render with errors. 
    end 
    end 
end 
0

另一种解决方案:

class Example < ActiveRecord::Base 
    DEFAULTS = HashWithIndifferentAccess.new(:some => 'default', :values => 'here') 

    def initialize(params = {}) 
    super(DEFAULTS.merge(params)) 
    end 
end 

要么使用初始化和合并参数,要么像使用before_create一样使用ActiveRecord钩子等。

相关问题