環境
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