[Rails] Put together the same code with controller actions

Put the same code into a method.

Before summarizing

controller.erb


  def edit
    @post = Post.find(params[:id])
  end

  def show
    @post = Post.find(params[:id])
  end

After summarizing

Write set_post in private and call it with before_action.

controller.erb



before_action :set_post, only: [:edit, :show]

  def edit
  end

  def show
  end

private
  def set_post
    @post = Post.find(params[:id])
  end

Recommended Posts

[Rails] Put together the same code with controller actions
Rails: 7 basic actions defined on the controller
Limit files created with the rails g controller command
[Rails] Put the same restrictions on multiple pieces of information
Understand code coverage with Rspec, the Ruby on Rails test framework
Put Zabbix in Ubuntu with Docker and monitor Docker on the same host
Generate Dart client code with Rails + apipie
Try using the Rails API (zip code)
[rails] List of actions defined in Controller
Prepare the format environment with "Rails" (VScode)
[Ruby on Rails] Controller test with RSpec
Check the processing contents with [rails] binding.pry
I rewrote the Rails tutorial test with RSpec
Use with_options to group the same validations together!
[Rails] Organize your code neatly with gem active_decorator
Publish the app made with ruby on rails
Understanding the MVC framework with server-side Java 3/4 Controller
The code I used to connect Rails 3 to PostgreSQL 10
Implement the Like feature in Ajax with Rails.
Determine the current page with Ruby on Rails
Try to summarize the common layout with rails