LoginSignup
82
66

More than 5 years have passed since last update.

かっこよくredirectかつreturn in rails

Posted at

Railsのコントローラーで、redirectして更にその後の処理をしたくないときはかなりあると思います。
そんなとき僕は今まで

users_controller.rb
def show
  @user = User.find params[:id]
  if @user.nil?
    redirect_to :root
    return
  end
end

と書いていて、ただのチェックの処理に4行も使っているのがすごく不満だったのですが

users_controller.rb
def show
  @user = User.find params[:id]
  return redirect_to :root if @user.nil?
end

このようにreturn redirect_to ... if ...と書けば一行で、更にかっこ良く書けることに今更ながら気づきました。

82
66
1

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
82
66