LoginSignup
2
1

More than 5 years have passed since last update.

Railsの学習 ~deviseを利用したユーザー登録

Last updated at Posted at 2018-05-22

deviseを利用したユーザー登録機能の実装メモ

今回はユーザーの登録に
・ユーザー名
・メールアドレス
・パスワード
を設定します。

・まずはgemをインストール

gemfile
gem 'devise'
$ bundle install


$ rails g devise:install

インストールすると、ターミナルに以下のような手順が表示される。

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here 
     is an example of default_url_options appropriate for a development environment 
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { :host => 'localhost:3000' }

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root :to => "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. If you are deploying Rails 3.1 on Heroku, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

手順1
メール送信機能のための設定。
ユーザー登録時にメールでの認証確認を行うときに使うとかそういうやつ。
とりあえず

config/environments/development.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

一番下にでも記入しておく。

手順2
トップページのルーティングを設定してね的な感じ

routes.rb
root 'home#top'

手順3
フラッシュメッセージとかエラーメッセージの表示の設定
入れなくても動作には問題なさそうだけど、
rayouts/application.html.erbの<body>タグの中に
に記述しておく

rayouts/application.html.erb
<body>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
<%= yield %>
</body>

手順4
Rails3.1でHerokuを使うなら~みたいなことが書いてあるので今回は必要なしと判断

手順5
deviseを導入すると、ユーザー登録、ログインに必要なviewも自動で作成してくれるが、フォルダ以下には生成されないので
作成されたviewを編集するには指定されたコマンドを実行する。

$ rails g devise:views

これでviewフォルダにdeviseで使用されるviewファイルがコピーされる。

・ここまでやったらユーザーモデルを作成していく。

$ rails g devise user

コマンドを入力するとマイグレーションファイルが作成されるので、デフォルトで使う場合はそのままdb:migrateする

deviseはデフォルトではメールアドレスとパスワードのカラムしかないので必要なものを作成されたマイグレーションファイルに追記するか

add_column:user,:カラム名,:データ型 で追加する

作成されたマイグレーションファイル(一部抜粋)

db/migrate/timestamp_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :username,           null: false, default: ""  #ユーザー名を入れるためのカラムを追加
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

・ファイルに追記したらmigrateする

$ rake db:migrate

null: false でバリデーションチェックされると思ったんだけど、ユーザー名を空にしても登録できてしまったので、手動でバリデーションを追記

app/models/user.rb
validates :username, presence: true

・viewファイルへユーザー名を登録するためのフォームを追加する

deviseで利用するviewは
新規登録の場合 app/views/devise/registrations/new.html.erb

app/views/devise/registrations/new.html.erb
#form_for以下に記述
    <div class="field">
          <%= f.label :username %><br />
          <%= f.text_field :username, autofocus: true %>
        </div>

必要であればログインフォームも同様に編集する
使用するviewは 
app/views/devise/sessions/new.html.erb

・Strong Parametersでusernameを許可する
deviseでの処理を調整したい場合はコントローラーを編集する必要があるが、ファイルとしては生成されていないため

app/controller/registrations_controller.rb
のような形で手動で追加するか

$ rails g devise:controllers users

とコマンドで生成する必要がある

コントローラーを編集した場合は

routes.rb
devise_for :users, :controllers => {
 :registrations => 'users/registrations'
}

のようにルーティングを設定する。

・Strong Parametersの設定

users/registrations_controller.rb

private

  def sign_up_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end

これで基本的なユーザー登録機能は実装できるはず。
抜け漏れ間違い等あれば指摘いただけると助かります。

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