Controller 重构套路 1 - before_action

在一个常见的CRUD controller, 经常会出现一行类似下面的代码

@group = Group.find(params[:id])

经常出现在 show edit update destroy 里面
修改前代码

app/products_controller.rb
class GroupsController < ApplicationController

  def index
    @groups = Group.all
  end
  
  def new
    @group = Group.new
  end

  def show
    @group = Group.find(params[:id])
  end

  def edit
    @group = Group.find(params[:id])
  end

  def create
    @group = Group.new(group_params)

    if @group.save
      redirect_to groups_path
    else
      render :new
    end
  end

  def update
    @group = Group.find(params[:id])
    if @group.update(group_params)
      redirect_to groups_path, notice: 'Update Success'
    else
      render :edit
    end
  end

  def destroy
    @group = Group.find(params[:id])

    @group.destroy
    redirect_to groups_path, alert: 'Group deleted'
  end

  private

  def group_params
    params.require(:group).permit(:title, :description)
  end
end

修改方法,在private下面新定义一个函数find_group, 然后before_action 中声明哪些action可以使用这个函数

app/products_controller.rb
class GroupsController < ApplicationController

  before_aciton :find_group, only: [:show, :edit, :update, :destroy]
  
  def index
    @groups = Group.all
  end

  def new
    @group = Group.new
  end

  def show
  end

  def edit
  end

  def create
    @group = Group.new(group_params)

    if @group.save
      redirect_to groups_path
    else
      render :new
    end
  end

  def update
    if @group.update(group_params)
      redirect_to groups_path, notice: 'Update Success'
    else
      render :edit
    end
  end

  def destroy

    @group.destroy
    redirect_to groups_path, alert: 'Group deleted'
  end

  private

  def group_params
    params.require(:group).permit(:title, :description)
  end
  
  def find_group
    @group = Group.find(params[:id])
  end
end

使用before_action 的方法修改JD-store中的product,order,category controller

Controller 重构套路 2 - 继承Inherite

不同的controller都有同样的几个关于action的代码

app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_required
  layout "admin"  
end
app/controllers/admin/orders_controller.rb
class Admin::OrdersController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_required
  layout "admin"      
end

利用继承,新增一个AdminController

rails g controller admin 
app/controllers/admin_controller.rb
class AdminController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_required

  layout "admin"

end

在其余的controller里面删除这些代码,采用 < 继承的方法,就是< AdminController
修改后的代码为

app/controllers/admin/products_controller.rb
class Admin::ProductsController < AdminController      # 继承AdminController 的特性

end
app/controllers/admin/orders_controller.rb
class Admin::OrdersController < AdminController        # 继承AdminController 的特性  

end