Ruby on rails Rails重构:在某些控制器中重复代码。它属于哪里?

Ruby on rails Rails重构:在某些控制器中重复代码。它属于哪里?,ruby-on-rails,refactoring,helper,actioncontroller,Ruby On Rails,Refactoring,Helper,Actioncontroller,我有类似的(重复?)代码出现在一些控制器中。有时在#update操作中,有时在#update#u multiple操作中……有时两者都有 在所有情况下,代码的主要目的是设置所属关系,因此有效地只在控制器模型上设置产品id。它使用first\u或\u create,因此如果引用的产品不存在,则首先创建该产品 重复代码: product = Product.where(params[:product]).first_or_create if params[:product] if product &

我有类似的(重复?)代码出现在一些控制器中。有时在
#update
操作中,有时在
#update#u multiple
操作中……有时两者都有

在所有情况下,代码的主要目的是设置
所属关系,因此有效地只在控制器模型上设置产品id。它使用
first\u或\u create
,因此如果引用的
产品不存在,则首先创建该产品

重复代码:

product = Product.where(params[:product]).first_or_create if params[:product]
if product && params[:project][:code].present?
  project = Project.where(params[:project]).first_or_create 
  product.project = project if project
end
product.save if product
快速概述或关系:\u项目&\u文件
属于
a产品。产品可以
属于
a项目

我可以/应该将此提取到哪里?我不确定它是否应该进入产品(和项目)模型?或者在ApplicationController中?还是帮手

下面是一些“野生”中的代码示例:

#disk_files_controller.rb
  ...
  def update
    product = Product.where(params[:product]).first_or_create if params[:product]
    if product && params[:project][:code].present?
      project = Project.where(params[:project]).first_or_create
      product.project = project if project
    end
    product.save if product

    respond_to do |format|
      if @disk_file.update(disk_file_params)
        format.html { redirect_to @disk_file, notice: 'Disk_File was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @disk_file.errors, status: :unprocessable_entity }
      end
    end
  end
多次更新的示例

#inventory_items_controller.rb
  ...
  def update_multiple
    product = Product.where(params[:product]).first_or_create if params[:product]
    if product && params[:project][:code].present?
      project = Project.where(params[:project]).first_or_create 
      product.project = project if project
    end
    product.save if product

    @inventory_items = InventoryItem.find(params[:inventory_item_ids])
    update_hash = {product_id: product.id}
    update_hash.merge({project_code: params[:project][:code]}) unless params[:project][:code].blank?
    InventoryItem.update_all(update_hash, {id: params[:inventory_item_ids]})
    redirect_to inventory_items_url
  end
  ...

我个人会将其提取到您的
产品中
型号:

class Product
  def self.first_or_create_by_params(params)
    # code here, return product
  end
end
然后在控制器中:

Product.first_or_create_by_params(params)

工作!虽然方法应该是
self.first_或\u create_by_params(params)
,因为它是一个类方法。