Ruby on rails RubyonRails:在控制器(或者可能是模型?)
我正在尝试使属性等于预定值,但我不确定是否通过以下方式(在我的orders controller中)有效地实现了这一点:Ruby on rails RubyonRails:在控制器(或者可能是模型?),ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试使属性等于预定值,但我不确定是否通过以下方式(在我的orders controller中)有效地实现了这一点: 有没有一种更有效的方法来等同Rails中的属性(可能使用模型)?如果我使用两个不同的控制器,我是否要重复我在新控制器上所做的操作 使用在模型中创建回调之前指定默认值。使用在模型中创建回调之前指定默认值。您的代码有点不正确,它看起来像是用于创建的控制器操作,但代码读起来像是用于更新 不管怎样。。。 您可以使用参数散列一次更新所有内容 在您正在创建的情况下: order_upda
有没有一种更有效的方法来等同Rails中的属性(可能使用模型)?如果我使用两个不同的控制器,我是否要重复我在新控制器上所做的操作 使用在模型中创建回调之前指定默认值。使用在模型中创建回调之前指定默认值。您的代码有点不正确,它看起来像是用于创建的控制器操作,但代码读起来像是用于更新 不管怎样。。。 您可以使用参数散列一次更新所有内容 在您正在创建的情况下:
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
您的代码有点不正确,它看起来像是用于创建的控制器操作,但代码读起来像是用于更新 不管怎样。。。 您可以使用参数散列一次更新所有内容 在您正在创建的情况下:
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
另一个解决方案:
class Example < ActiveRecord::Base
DEFAULTS = HashWithIndifferentAccess.new(:some => 'default', :values => 'here')
def initialize(params = {})
super(DEFAULTS.merge(params))
end
end
类示例default',:values=>here)
def初始化(参数={})
超级(默认值。合并(参数))
结束
结束
使用initialize和merge with params,或使用ActiveRecord钩子,如创建前等。另一种解决方案:
class Example < ActiveRecord::Base
DEFAULTS = HashWithIndifferentAccess.new(:some => 'default', :values => 'here')
def initialize(params = {})
super(DEFAULTS.merge(params))
end
end
类示例default',:values=>here)
def初始化(参数={})
超级(默认值。合并(参数))
结束
结束
可以使用initialize和merge with params,也可以使用ActiveRecord钩子,比如在创建之前等等