toshizou-Rails

_links.html.erbの中身について

_links.html.erbとは

Railsでよく使うgem devise でジェネレータコマンドを実行すると自動生成されるファイルです。

Deviseとは

個人開発で使っていない人はいないんじゃないかというぐらい便利な認証系を簡単に実装できるgemです。

ユーザー登録して、送られてきたメールのリンクをクリックして本登録して、ログインして、パスワード忘れたら再設定して、何回もログインミスったらアカウントロックして…などといった認証系アプリに必要な機能を簡単に追加できる便利なgemです。 [Rails] deviseの使い方(rails5版) - Qiita

なぜ書くつもりになったのか?

理由は

  • 個別ページで_links.html.erbの中のリンクをコピペすることがある
  • if文とcontrollerの記述が多くて探すのに少しだけ時間がかかる(ときどき忘れる)

といった感じです。

今回はコードだけ掲載しておけば大丈夫だと思うので下記を参考にすればいいと思います。

<%# ログイン(sessions/new) %>
<%- if controller_name != 'sessions' %>
  <%= link_to "Log in", new_session_path(resource_name) %><br />
<% end %>
<%# 新規登録(registrations/new) %>
<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
  <%= link_to "Sign up", new_registration_path(resource_name) %><br />
<% end %>
<%# パスワードを忘れた場合(passwords/new)) %>
<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
  <%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
<% end %>
<%# 確認メールを受け取っていない場合or再送(confirmations/new) %>
<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
  <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
<% end %>
<%# アカウントロックを解除するためのメール送信画面(unlocks/new.html.erb) %>
<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
  <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
<% end %>

<%# SNS系による認証(各SNSのAPIkeyなどが必要にあなる) %>
<%- if devise_mapping.omniauthable? %>
  <%- resource_class.omniauth_providers.each do |provider| %>
    <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %><br />
  <% end %>
<% end %>