0

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

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
4

1 回答 1

0

您可以采取以下几种方法来实现您想要的目标:

  1. 研究使用嵌套表单accepts_nested_attributes_for. 使用嵌套属性,您的控制器edit方法只需要@shipment与 shipping_products 的嵌套集合共享一个实例变量。
  2. 考虑让你的update行动只打电话update_attributes。当您正确使用嵌套属性时,这应该是您需要的唯一模型调用,因为它将隐式填充其shipment_products.
  3. 在您的shipment_products模型中,使用after_save回调来标记未结发货。但请注意,您的 shipping_products 模型不应使用单词Product(大写)。相反,它应该依赖于它belongs_to与 call的关系product.mark_open_shipment(difference)difference应该重构为 product_shipments 上的实例方法。回调和 update_attributes 都将在一个事务中运行,这将确保原子性。
于 2012-10-16T04:15:55.343 回答