3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Deviseでログイン前のルーティングを設定する

Posted at

#やりたいこと
Devise導入した状態で、
ログイン前後のルーティングをカスタマイズする。

#前提
Deviseをインストールすると、デフォルトではルートパスが/users/sign_inとなっている。
そのため、ログインしていない状態でtopページへ行こうとするとdevise側で勝手にサインインページに飛んでしまう。

#方法
ログインしていない状態で特定のページへ遷移させたい場合は
before_action :authenticate_user!
を該当コントローラーに記述する必要があります。
全てのアクションについてログイン認証を必要とする場合はapplication_controllerに記述することで
各コントローラーに記述する手間を省けます。

#before_action :authenticate_user!とは
before_action :authenticate_user!はdeviseのヘルパーメソッドです。
これを記述することで認証ユーザーのみ各アクションを実行するようになります。

#特定のアクションのみ、ログインしていない状態で実行したい場合
例えば「topページとaboutページだけはログインしていなくても表示させたい…」という時は
下記のように、該当アクションを除外する形で指定します。

authenticate_user!, except: [:top, about]

こうすることでtopアクションとaboutアクションのみログアウト状態でも表示することができます。
その他のアクションはログインしていないとURL直打ちしても表示されなくなります。

▼参考Devise authentication_user!
https://skillhub.jp/courses/137/lessons/978

又、今回私はapplication_controllerに記述すると記載しましたが、
userコントローラー以外の他のコントローラーにログイン認証設定を加えたくない場合は
ディレクトリに階層を作り、そのディレクトリのみ適応されるコントローラーを作成する方法もあります。

下記を参考にしてください。
▼参考
https://qiita.com/ryuuuuuuuuuu/items/bf7e2ea18ef29254b3dd

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?