0
0

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 5 years have passed since last update.

Ruby on Rails [学習記録-第7章-]

Posted at

ログイン機能の実装

devise

  • deviseは、ログイン機能を簡単に作成することができるGem。
  • deviseを使用するためには、Gemのインストールに加えてdevise専用のコマンドを利用して設定ファイルを作成する必要がある。
$ rails g devise:install
  • deviseを利用する際にはアカウントを作成するためのUserモデルを新しく作成する。

rails g devise コマンド

  • deviseでログイン機能をつける概念のモデルを作成する際に利用するコマンド。モデルに加えて、ログイン機能のために必要なカラムが追加されるマイグレーションファイルなどが生成される。
$ rails g devise user
# deviseコマンドでモデルを作成
  • config/routes.rbに以下の様な記述が自動的に追記される。
routes.rb
Rails.application.routes.draw do
  devise_for :users
# 以下略
  • devise_forはログインまわりに必要なルーティングを一気に生成してくれるdeviseのヘルパーメソッド。
  • 後ほど登場するcurrent_userやuser_signed_in?などのヘルパーメソッドも利用できるようになる。

link_toメソッド

  • このメソッドは引数を指定することで様々なリンクを生成できる。
  • 通常HTMLコード内でリンクを生成する際にはaタグを使用する。link_toメソッドを使って記述を行うと、HTMLコードが読み込まれる際にaタグに変換されるので、サイトを表示した際にはaタグと同様に、リンクとして表示される。
sample.html.erb
  <%= link_to 'ツイート一覧へ', '/tweets', class: 'sample' %>
  # 作成したaタグに`class="sample"`属性を付与

user_signed_in?

  • deviseでログイン機能を実装すると、user_signed_in?というメソッドを使用することができる。
  • ユーザーがサインインしているかどうか検証するメソッド。
  • サインインしている場合にはtrueを返し、サインインしていない場合にはfalseを返す。
sample.html.erb
<% if user_signed_in? %>
  # ユーザーがサインインしている場合に実行する処理
<% end %>

Prefix

  • Prefix(プレフィックス)とは、ルーティングのパスが入る変数のこと。コントローラやビューなどで呼び出すことで、prefixに入っているパスやURL情報を取得できるようになる。
  • deviseを導入した場合、ユーザーの新規登録やログインに関するprefixは予め決まっており、以下のようになる。
リクエスト prefix パス
devise/sessions#new    new_user_session /users/sign_in
devise/sessions#create   user_session /users/sign_in
devise/sessions#destroy destroy_user_session /users/sign_out

redirect_toメソッド

  • Railsでは通常、アクション内の処理が終了すると自動的にアクション名と同名のビューが表示される。
  • ただしredirect_toメソッドをアクション内で利用すると、そこからさらに別のアクションを実行したり、ビューに遷移させたりできる。
  • 引数にはaction: :indexという形で、キーがaction:バリューが:indexであるハッシュを指定する。
apps_controller.rb
class AppsController < ApplicationController

  def index
    @apps = App.page(params[:page]).per(5).order("created_at DESC")
  end

  private
  def move_to_index
    redirect_to action: :index
    # indexアクションを強制的に実行する
  end
end

before_action

  • Railsではコントローラでbefore_action :メソッド名と記述することで、コントローラのアクションが実行される前にそのメソッドを実行することができる。
  • また、オプションonlyやexceptを使うことにより、before_actionを実行することをアクションごとに制限をかけることができる。
apps_controller.rb
class AppsController < ApplicationController

  before_action :hoge, except: :index
  # indexアクション以外が実行される前にhogeが実行される。

  def index
    @apps = App.page(params[:page]).per(5).order("created_at DESC")
  end

  private
  def hoge
  end
end
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?