0
0

More than 1 year has passed since last update.

【Rails】コントローラーの処理を共通化したい

Posted at

環境

Ruby 3.0.2
Rails 6.1.4.1

共通化する前

UsersControllerとHomeControllerともに同じコードがあるので共通化したい。

posts_controller.rb
class PostsController < ApplicationController
  def index
    @post = current_user.post
  end
end
home_controller.rb
class HomeController < ApplicationController
  def index
    @post = current_user.post
  end
end

共通化した後

共通化したいコードをconcerns下にメソッドとして定義する。

concerns/common_action.rb
module CommonAction
  extend ActiveSupport::Concern

  def set_posts
    @posts = current_user.posts
  end
end
home_controller.rb
class HomeController < ApplicationController
  include CommonAction

  def index
    set_posts
  end
end
users_controller.rb
class UsersController < ApplicationController
  include CommonAction

  def index
    set_posts
  end
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0