LoginSignup
26
19

More than 5 years have passed since last update.

Railsでログイン時のルーティングを定義する(deviseのauthenticatedみたいなやつ)

Posted at

deviseを使うとconfig/routes.rbに

config/routes.rb
Rails.application.routes.draw do
  authenticated :user do
    root to: 'dashboard#show', as: :user_root
  end

  root to: 'landing#show'
end

こんな感じで、ログイン時とそうでない時のルーティングが書けます。

authenticated-instance_method
http://www.rubydoc.info/github/plataformatec/devise/master/ActionDispatch/Routing/Mapper#authenticated-instance_method

これをdevise以外で実現したい時は、constraintsで実現できます。

config/routes.rb
class AuthenticatedConstraint
  def matches?(request)
    request.session['user_id'].present?
  end
end

Rails.application.routes.draw do
  constraints AuthenticatedConstraint.new do
    root to: 'dashboard#show', as: :user_root
  end

  root to: 'landing#show'
end

便利(\( ⁰⊖⁰)/)

26
19
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
26
19