helper_method

実装

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def current_site
    # @current_siteがnillであれば、Site.firstを代入する。
    @current_site ||= Site.first
  end
  helper_method :current_site
end

このようにApplicationControllerに定義します。 今後コントローラとビューの両方から利用する機会がある場合、helper_methodでメソッド名を宣言しておくととても便利です。

class Admin::SitesController < ApplicationController
  layout 'admin'

  before_action :set_site

  def edit
    authorize(@site)
  end

  def update
    authorize(@site)

    if @site.update(site_params)
      redirect_to edit_admin_site_path
    else
      render :edit
    end
  end

  private

  def site_params
    params.require(:site).permit(:name, :subtitle, :description, :favicon, :og_image)
  end

  def set_site
    @site = Site.find(current_site.id)
  end
end