I have similar (duplicate?) code appearing in a few controllers. Sometimes it's in the #update action, sometimes it's in an #update_multiple action...and sometimes it's in both.

In all cases it's code that's primary purpose is to set the belongs_to relationship, so effectively only setting the product_id on the controller's model. It uses first_or_create so if referenced Product does not exist then it is created first.

duplicate code:

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

Quick overview or relationships: _Items & _Files belong_to a Product. Products can belong_to a Project.

Where can/should I extract this to? I'm not sure if it should go into the Product (and Project) models? or perhaps in ApplicationController? Or a helper?

Here's some examples of the code in the 'wild':

#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

example of 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
  ...
有帮助吗?

解决方案

I'd personally extract it into your Product model:

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

Then in your controller:

Product.first_or_create_by_params(params)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top