我在修饰控制器时遇到的大多数问题都涉及简单的模型关系。我的问题是,如果您使用多个参数及其关联的数组更新多对多的表单,那么如何通过将其全部移动到模型方法来简化任务?例如,看看下面那个可笑的大型控制器。处理这种邪恶混乱的最简单方法是什么?我不是在寻找语法上完美的答案,但需要就这个方向达成一致意见。
def update
@shipment = Shipment.joins(:products).find(params[:id], :readonly => false)
@shipment.update_attributes(params[:shipment])
@shipment_products = params[:product_shipments]
@product_shipment_array= array_from_hash(@shipment_products)
@shipment.product_shipments.each do |product_shipment|
product_shipment.update_attributes(:qty_shipped => params[:product_shipments][product_shipment.id.to_s][:qty_shipped], :pickup_item => params[:product_shipments][product_shipment.id.to_s][:pickup_item])
end
@product_shipment_array.each do |p|
if p['old_pickup_item'] == "true" and p['pickup_item'].to_i==0
@difference = (p['qty_shipped'].to_i)
Product.mark_open_shipment(@difference, p['product_id'])
elsif p['old_pickup_item'] == "false" and p['pickup_item'].to_i==1
@difference = -(p['old_qty_shipped'].to_i)
Product.mark_open_shipment(@difference, p['product_id'])
else
@difference = -(p['old_qty_shipped'].to_i - p['qty_shipped'].to_i)
Product.mark_open_shipment(@difference, p['product_id'])
end
end
respond_with @shipment, :location => shipments_url
end
在我的模型中,我想声明一个像这样的模型方法
Class Shipment < ActiveRecord::Base
.
.
.
def update_shipment_attributes
#all business logic
end
end
希望让我的控制器达到类似这样或类似的东西:
def update
@shipment = Shipment.joins(:products).find(params[:id], :readonly => false)
@shipment.update_attributes(params[:shipment])
@shipment_products = params[:product_shipments]
Shipment.update_shipment_attributes
respond_with @shipment, :location => shipments_url
end
答案 0 :(得分:0)
您可以采取以下几种方法来实现您的目标:
accepts_nested_attributes_for
。使用嵌套属性,您的控制器edit
方法只需要与一个嵌套的shipment_products集合共享一个@shipment
实例变量。update
操作只调用update_attributes
。当您正确使用嵌套属性时,这应该是您需要的唯一模型调用,因为它将隐式填充其shipment_products
的属性。shipment_products
模型中,使用after_save
回调标记打开的货件。但要注意,您的shipment_products模型应该不使用单词Product
(大写)。相反,它应该依靠belongs_to
关系来调用product.mark_open_shipment(difference)
。 difference
应该重构为product_shipments上的实例方法。回调和update_attributes都将在一个事务中运行,这将确保原子性。