コードをまとめかた
controller.rbの記述が繰り返し書かれているときは、before_actionを使用して、メソッドとしてまとめます。
【例】モデル名がPostのとき
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 :処理させたいメソッドの名前
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_メソッドを使います。
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アクションを実行します。