0
0

More than 1 year has passed since last update.

railsチュートリアル第七章 ユーザー登録失敗

Posted at

ユーザー登録失敗

フォームを理解するにはユーザー登録の失敗のときが最も参考になる。
この節では、無効なデータ送信を受け付けるユーザー登録フォームを作成し、ユーザー登録フォームを更新してエラーの一覧を表示します。

正しいフォーム

Rails.application.routes.draw do
  root 'static_pages#home'
  get  '/help',    to: 'static_pages#help'
  get  '/about',   to: 'static_pages#about'
  get  '/contact', to: 'static_pages#contact'
  get  '/signup',  to: 'users#new'
  resources :users
end

urlにusersを入れることができる。
それによりcreateアクションを使い、新規作成者を作ることができたりした。

<form action="/users" class="new_user" id="new_user" method="post">

POSTリクエストを/usersというURLに送信

ユーザー登録の失敗に対応できるcreateアクション

class UsersController < ApplicationController
.
.
.
  def new
    @user = User.new
    #新しくユーザーオプジェクトを作成する
    # オブジェクトの属性をつける
  end

  def create
    @user = User.new(params[:user])    # 実装は終わっていないことに注意!
    if @user.save
      # 保存の成功をここで扱う。
    else
      render 'new'
      # 保存に成功しなければnewアクションに移動する
    end
  end
end

プレビューで確認 失敗
ActiveModel::ForbiddenAttributesError in UsersController#create
createアクションで失敗したらしい。

Request
Parameters:

{"authenticity_token"=>"dfo0Ltyd8b+HqfZYMQ4dsyiL4b1FM0LqBY3mAQfni3QmVBfVE7B9kwrZIQ3kuT/QLU/He+TpHuJQrkuWwFvUNw==",
 "user"=>{"name"=>"", "email"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"},
 "commit"=>"Create my account"}

Usersコントローラにparamsとして渡されます

<input id="user_email" name="user[email]" type="email" />

"user[email]"という値は、userハッシュの:emailキーの値と一致

2つのコードの意味は一緒らしい。

@user = User.new(params[:user])
@user = User.new(name: "Foo Bar", email: "foo@invalid",
                 password: "foo", password_confirmation: "bar")

昔のバージョンのRailsでは、次のコードでも動いた。

@user = User.new(params[:user])

しかし悪意からの対策としてわざとエラーを起こすStrong Parametersという技術で今は動かない。

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