Rails 3.2使用has_many上的模型方法简化控制器:通过

时间:2012-10-16 02:51:32

标签: ruby-on-rails model controller refactoring ruby-on-rails-3.2

我在修饰控制器时遇到的大多数问题都涉及简单的模型关系。我的问题是,如果您使用多个参数及其关联的数组更新多对多的表单,那么如何通过将其全部移动到模型方法来简化任务?例如,看看下面那个可笑的大型控制器。处理这种邪恶混乱的最简单方法是什么?我不是在寻找语法上完美的答案,但需要就这个方向达成一致意见。

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

1 个答案:

答案 0 :(得分:0)

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

  1. Look into using nested formsaccepts_nested_attributes_for。使用嵌套属性,您的控制器edit方法只需要与一个嵌套的shipment_products集合共享一个@shipment实例变量。
  2. 考虑让您的update操作只调用update_attributes。当您正确使用嵌套属性时,这应该是您需要的唯一模型调用,因为它将隐式填充其shipment_products的属性。
  3. shipment_products模型中,使用after_save回调标记打开的货件。但要注意,您的shipment_products模型应该使用单词Product(大写)。相反,它应该依靠belongs_to关系来调用product.mark_open_shipment(difference)difference应该重构为product_shipments上的实例方法。回调和update_attributes都将在一个事务中运行,这将确保原子性。