As the number of site pages increases, the description of the same controller will increase. If you use concerts at that time, the description will be cleaner and the readability will be improved.
app/controllers/posts_controller.rb
class PostController < ApplicationController
before_action :set_posts
def set_posts
@posts = Post.all
end
end
app/controllers/users_controller.rb
class UserController < ApplicationController
before_action :set_posts
def set_posts
@posts = Post.all
end
end
As mentioned above, there is a common process called set_posts. However, if there is a change, both must be corrected, which is a hassle. The way to solve these is to use concerns.
Create a file under app / controllers / concerts. This time, the file name will be "postable.rb".
app/controllers/concerns/postable.rb
module Postables
extend ActiveSupport::Concern
def set_posts
@posts = Post.all
end
end
And to call each controller
include postables
It is described as.
app/controllers/posts_controller.rb
class PostController < ApplicationController
include Postables
before_action :set_posts
end
app/controllers/users_controller.rb
class UserController < ApplicationController
include Postables
before_action :set_posts
end
This is OK.
By doing these, even if there is a correction, you only need to correct it in one place, and you can respond immediately even if an error occurs. It is recommended to use it because the lack of description leads to maintainability.
Also, on twitter, technologies and ideas that have not been uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork
Recommended Posts