LoginSignup
0
1

More than 1 year has passed since last update.

【Rails】deviseのviewsをカスタマイズする方法

Last updated at Posted at 2022-05-06

Rails6で$ rails generate devise:viewsをして得たデフォルトのviewsをカスタマイズしようとしたらうまくいかなかったです。

deviseのgithubをみてみると下記の文が書いていました。

If you have more than one Devise model in your application (such as User and Admin), you will notice that Devise uses the same views for all models. Fortunately, Devise offers an easy way to customize views. All you need to do is set config.scoped_views = true inside the config/initializers/devise.rb file.

和訳すると。

一つ以上のDevise modelを持っている場合、Deviseは複数のmodelに対し、同じviewsを使用するが、Deviseはviewsをカスタマイズする簡単な方法を提供している。下記のようにコードを変更するだけ!

config/initializers/devise.rb
config.scoped_views = true

上記のようにコード変更を行なって、views/devise/registrationsshow.html.slimを追加して、routes.rbも下記のように変更しましたが、エラーになりました。

routes.rb
# エラーになったrouting
 get 'user/show', to: 'sessions/users#show' 

Routing エラー

エラーの詳細は下記になります。
image.png

エラー対応

対応策はエラー詳細に書いていますが、詳しく知るために、もう1度deviseのgithubをみました。
下記の文がありまね。なるほど、deviseのやり方があるみたいですね。

If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is create your routes normally and wrap them in a devise_scope block in the router:

和訳すると。

もっとroutingをカスタマイズしたいのであれば、routesを下記のようにdevise_scope blockに入れる必要がある。
コード例は下記↓

route.rb
devise_scope :user do
  get 'sign_in', to: 'devise/sessions#new'
end

Please note: You will still need to add devise_for in your routes in order to use helper methods such as current_user.

そして注意すべきところを和訳すると、

current_userのようなメソッドを使うためにはroute.rbdevise forを追加しとく必要がある。

説明通り、下記のようにコードを変更したらエラーが消えまて、routingも問題なくできましたし、current_userのメソッドも使うことができました。

routes.rb
Rails.application.routes.draw do

  devise_for :users
  devise_scope :user do
    get "/user/show" => "sessions/users#show"
    end

ご指摘等ございましたら、教えてください。
読んでくださってありがとうございました。

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