0
3

More than 3 years have passed since last update.

controller.rbでのコードをまとめかた

Last updated at Posted at 2020-03-04

コードをまとめかた

controller.rbの記述が繰り返し書かれているときは、before_actionを使用して、メソッドとしてまとめます。
【例】モデル名がPostのとき

app/controllers/posts_controller.rb
class TweetsController < ApplicationController

  def index
    @posts = Post.all
  end
〜略〜
  def show
    @post = Post.find(params[:id])
  end

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

  def update
    post = Post.find(params[:id])
    post.update(post_params)
  end

〜略〜
end

上記の記述だとshowとeditの中身が一緒なので、before_actionを使用します。

before_action

コントローラのすべてのアクションで実行の前に共通の処理を行いたいときに、before_actionを使用すると全てのアクションが実行される前に指定したメソッドを呼び出すことができるのが。before_actionです。
resourcesと同様にonlyやexceptでどのアクションの時に呼び出すか限定することができます。
今回はshowとeditをset_postメソッドで定義していきます。

【例】

before_action :処理させたいメソッドの名前
app/controllers/posts_controller.rb
class TweetsController < ApplicationController
  before_action :set_post, only: [:edit, :show]

  def index
    @posts = Post.all
  end
〜略〜
  def show
  end

  def edit
  end

  def update
    post = Post.find(params[:id])
    post.update(post_params)
  end

〜略〜

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

上記のようにshowとeditをset_postとbefore_actionを使いまとめてみました。

move_to_メソッド

ユーザーがログインしていないときにindexアクションにリダイレクトするときはmove_to_メソッドを使います。

app/controllers/posts_controller.rb
class TweetsController < ApplicationController
  before_action :set_post, only: [:edit, :show]
   before_action :move_to_index, except: [:index, :show]

  def index
    @posts = Post.all
  end
〜略〜
  def show
  end

  def edit
  end

  def update
    post = Post.find(params[:id])
    post.update(post_params)
  end

〜略〜

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

  def move_to_index
    redirect_to action: :index unless user_signed_in?
  end
end

indexアクションにアクセスした時、indexアクションへのリダイレクトを繰り返し無限ループが起こるので、except: :indexを付け加え、ログインする必要はないものはexcept: [:index, :show]としています。
unless user_signed_in?で判定をして、その返り値がfalseだった場合に手前の式を実行するということになります。
なのでユーザーがログインしていない時にはindexアクションを実行します。

0
3
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
3