0

いくつかのコントローラーに同様の (重複した?) コードが表示されています。ある時は#updateアクションの中にあり、ある時はアクションの#update_multiple中にあり、またある時は両方にある。

いずれの場合も、belongs_to関係を設定することが主な目的のコードであるため、効果的にはコントローラーのモデルに product_id を設定するだけです。first_or_create参照先Productが存在しない場合は、最初に作成されます。

重複コード:

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

簡単な概要または関係: _Items & _Files belong_to a Product . 製品はbelong_toProject にすることができます。

これをどこに抽出できますか/すべきですか? 製品 (およびプロジェクト) モデルに入るべきかどうかわかりませんか? またはおそらく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

update_multiple の例

#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
  ...
4

1 に答える 1

1

私は個人的にそれをあなたのProductモデルに抽出します:

class Product
  def self.first_or_create_by_params(params)
    # code here, return product
  end
end

次に、コントローラーで:

Product.first_or_create_by_params(params)
于 2013-08-28T20:53:40.627 に答える