我看到的大多数关于精简控制器的问题都涉及简单的模型关系。我的问题是,如果您要更新具有多个参数及其关联数组的多对多表单,您如何通过将其全部移动到模型方法来简化任务?例如,看看下面这个大得离谱的控制器。处理这种邪恶的混乱最简单的方法是什么?我不是在寻找一个语法上完美的答案,而是需要就一个方向达成普遍共识。
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