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 1 year has passed since last update.

deviseのサインアップにenumを使用したら, '0'is not a validとエラーが出る

Posted at

やりたいこと

  • Railsのユーザ認証を行うgem deviseでサインアップするモデルのカラムをenumにしたい
  • 該当するモデルのカラムはInteger型
# app/models/user.rb
class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  enum user_type: {
    user: 0,
    circle: 1
  }
end
# db/schme.rb
ActiveRecord::Schema[7.0].define(version: 2022_07_02_083714) do
  create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "user_type", default: 0, null: false
    t.string "name", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

発生した問題

  • sign up 画面を編集するために以下のようにapp/views/users/registrations/new.html.erbを編集したところ、ArgumentError in Devise::RegistrationsController#create '1' is not a valid hogeのエラーが表示され、ユーザ登録できなかった。
# app/views/users/registrations/new.html.erb

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render 'users/shared/error_messages', resource: resource %>

  <div class='field'>
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: 'email' %>
  </div>

  ...略...

  <div class='field'>
    <div>
      サークルとして登録
      <!--  チェック時は0, 未チェック時は1を送信するように設定 -->
      <%= f.check_box :user_type, {}, 0, 1 %>
    </div>
  </div>

  <div class='actions'>
    <%= f.submit 'Sign up' %>
  </div>
<% end %>

<%= render 'users/shared/links' %>


  • エラー画面
    Screen Shot 2022-07-07 at 7.12.21.png

解決策

  • app/views/users/registrations/new.html.erbのフォームをenumのキーに変更する
# app/views/users/registrations/new.html.erb
...略...

## フォーム部分のチェック時の値を指定する箇所を数値から
-- <%= f.check_box :user_type, {}, 0, 1 %>

## 以下のようにenumのキーにする
++ <%= f.check_box :user_type, {}, :circle, :user %>

参考

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?