Extract a Single Action Controller class

Before

resources :products
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def index
  end

  def show
  end

  def new
  end

  def edit
  end

  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
  end

  def destroy
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.require(:product).permit(:name, :description)
    end
end

After

post 'products' => 'create_product#create'
resources :products, except: [:create]
class CreateProductController < ApplicationController

  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    def product_params
      params.require(:product).permit(:name, :description)
    end
end

Algorithm

  1. A new route declaration above the previous (first wins)
  2. Create an empty controller CreateProductController which inherits from the previous
  3. Copy the action content to the new controller
  4. Remove the action from the previous controller
  5. Copy the filters/methods that are used by the action to the new controller
  6. Make the new controller inherit from the ApplicationController
  7. Change routes to add 'except: [:foo_action]'
Back to refactoring recipes