Rails4 - 如何验证我的webapp的Gender [boolean type]字段

时间:2014-10-30 13:00:46

标签: ruby-on-rails forms ruby-on-rails-4 boolean

我是rails的新手,并尝试将Gender添加到我使用Michael Hartl教程创建的现有应用程序

我决定对Gender使用boolean类型。 我在迁移文件中添加了新列

db / migrate / [timestamp] _add_admin_to_users.rb

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false

    #Start - Adding for gender and dob
    add_column :users, :date_of_birth, :datetime
    add_column :users, :is_female, :boolean, default: false
    #End - Adding for gender and dob

  end
end

使用我的新列

创建表格
$bundle exec rake db:migrate

决定创建选择框,因为我在重复尝试后无法创建单选按钮

应用/模型/ user.rb

class User < ActiveRecord::Base
.
.
GENDER_TYPES = [ ["Male","0"], [ "Female","1" ] ]
validates :is_female, presence: true, inclusion: { in: ["0","1"] }
.
.

更新了测试 的测试/模型/ user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.new(name: "Example User", email: "user@example.com",
                     password: "foobar", password_confirmation: "foobar", 
                     date_of_birth: "08/04/1987", is_female: "0")
  end
.
.

这是我的注册表单

视图中的选择框摘录

app / views / users / new.html.erb

<%= f.label :is_female, "Gender" %>
<%= f.select :is_female, User::GENDER_TYPES, class: 'form-control' %>

这是来自HTML注册表格的选择框摘录

              <div>
              <label for="user_is_female">Gender</label>
              <select id="user_is_female" name="user[is_female]"><option value="0">Male</option>
<option value="1">Female</option></select>
              </div>

添加以下内容以免受群发分配漏洞影响

应用/控制器/ users_controller.rb

class UsersController < ApplicationController
.
.
  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation, :is_female, :date_of_birth)
    end  
.
.

来自rails webrick server的日志

Started POST "/users" for 1.39.63.200 at 2014-10-30 12:26:54 +0000
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"_", "authenticity_token"=>"X1CF1B0ds3fn6QbPE4HhD/AAHo9n6D5+e8oHwgyiU4wSzV3hdUeKCE1Mr3PHJKYx7GPhwmpksYVxS/QmqpwjuQ==", "user"=>{"name"=>"Kumar", "email"=>"test12@test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "is_female"=>"1", "date_of_birth(1i)"=>"2017", "date_of_birth(2i)"=>"10", "date_of_birth(3i)"=>"30"}, "commit"=>"Create my account"}
   (0.1ms)  begin transaction
  User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('test12@test.com') LIMIT 1
   (0.1ms)  rollback transaction
  Rendered shared/_error_messages.html.erb (0.7ms)
  Rendered users/new.html.erb within layouts/application (8.0ms)
  Rendered layouts/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (0.6ms)
  Rendered layouts/_footer.html.erb (0.3ms)
Completed 200 OK in 681ms (Views: 571.3ms | ActiveRecord: 1.5ms)
1.39.63.200 - - [30/Oct/2014:12:26:55 +0000] "POST /users HTTP/1.1" 200 - 0.7922

来自浏览器中调试器的信息

--- !ruby/hash:ActionController::Parameters
utf8: "✓"
authenticity_token: X1CF1B0ds3fn6QbPE4HhD/AAHo9n6D5+e8oHwgyiU4wSzV3hdUeKCE1Mr3PHJKYx7GPhwmpksYVxS/QmqpwjuQ==
user: !ruby/hash:ActionController::Parameters
  name: Kumar
  email: test12@test.com
  password: testtest
  password_confirmation: testtest
  is_female: '1'
  date_of_birth(1i): '2017'
  date_of_birth(2i): '10'
  date_of_birth(3i): '30'
commit: Create my account
controller: users
action: create

当我尝试注册时,我得到以下内容

The form contains 1 error.

    Is female is not included in the list

我无法解决此错误。请帮助

- 更新 -

感谢@ user3243476,我更改了我的验证,如下所示

validates :is_female, presence: true, inclusion: { in: [true,false] }

我可以创建性别为女性的个人资料

Started POST "/users" for 1.39.61.148 at 2014-10-30 14:36:10 +0000
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"_", "authenticity_token"=>"KQVNN5mXph8gEeX+JmOGMLCtBcS2HFK8lh0QtSynHuZkmJUC8c2fYIq0TELyxsEOrM76ibuQ3UecnONRiplu0w==", "user"=>{"name"=>"test", "email"=>"etest@test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "is_female"=>"1", "date_of_birth(1i)"=>"2013", "date_of_birth(2i)"=>"10", "date_of_birth(3i)"=>"30"}, "commit"=>"Create my account"}
   (0.1ms)  begin transaction
  User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('etest@test.com') LIMIT 1
  SQL (0.8ms)  INSERT INTO "users" ("activation_digest", "created_at", "date_of_birth", "email", "is_female", "name", "password_digest", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["activation_digest", "$2a$10$QX6Hx/.bV1BHV955bA8WcuESL3GOBDwGl/o9wnE3EsVHRhwm11csW"], ["created_at", "2014-10-30 14:36:10.201241"], ["date_of_birth", "2013-10-30 00:00:00.000000"], ["email", "etest@test.com"], ["is_female", "t"], ["name", "test"], ["password_digest", "$2a$10$15qDvXmU4A3yGK/2lpUBQOazyAVb.3ulaYvPEReeJC76cdFrf5mo."], ["updated_at", "2014-10-30 14:36:10.201241"]]
   (12.0ms)  commit transaction
  Rendered user_mailer/account_activation.html.erb (1.3ms)
  Rendered user_mailer/account_activation.text.erb (0.5ms)

UserMailer#account_activation: processed outbound mail in 314.1ms

但我无法创建性别与男性相同的个人资料 我收到了一个新错误

The form contains 1 error.

    Is female can't be blank

这是webrick log

Started POST "/users" for 1.39.60.97 at 2014-10-30 15:45:05 +0000
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"_", "authenticity_token"=>"IAlJi57XunoNgnaEiTfZ7kIbMs9k4de2dBSzrNXU5fRtlJG+9o2DBacn3zhdkp7QXnjNgmltWE1+lUBIc+qVwQ==", "user"=>{"name"=>"newmale", "email"=>"newmale@test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "is_female"=>"0", "date_of_birth(1i)"=>"2017", "date_of_birth(2i)"=>"10", "date_of_birth(3i)"=>"30"}, "commit"=>"Create my account"}
   (0.1ms)  begin transaction
  User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('newmale@test.com') LIMIT 1
   (0.1ms)  rollback transaction
  Rendered shared/_error_messages.html.erb (5.9ms)
  Rendered users/new.html.erb within layouts/application (12.8ms)
  Rendered layouts/_shim.html.erb (0.0ms)
  Rendered layouts/_header.html.erb (0.5ms)
  Rendered layouts/_footer.html.erb (0.2ms)
Completed 200 OK in 1825ms (Views: 1584.9ms | ActiveRecord: 0.6ms)
1.39.60.97 - - [30/Oct/2014:15:45:07 +0000] "POST /users HTTP/1.1" 200 - 1.9334

调试器日志

--- !ruby/hash:ActionController::Parameters
utf8: "✓"
authenticity_token: IAlJi57XunoNgnaEiTfZ7kIbMs9k4de2dBSzrNXU5fRtlJG+9o2DBacn3zhdkp7QXnjNgmltWE1+lUBIc+qVwQ==
user: !ruby/hash:ActionController::Parameters
  name: newmale
  email: newmale@test.com
  password: testtest
  password_confirmation: testtest
  is_female: '0'
  date_of_birth(1i): '2017'
  date_of_birth(2i): '10'
  date_of_birth(3i): '30'
commit: Create my account
controller: users
action: create

在rails控制台中,我尝试了以下

无法保存男性用户

>> newmaleuser = User.new(name: "Example male User", email: "male@example.com", password: "foobar", password_confirmation: "foobar", date_of_birth: "08/04/1987", is_female: "0")
=> #<User id: nil, name: "Example male User", email: "male@example.com", created_at: nil, updated_at: nil, password_digest: "$2a$10$m8NsGUgNZ1fLqzba1JpWLuIlkM47ZpxMtUouMqMpIZP...", remember_digest: nil, admin: false, date_of_birth: "1987-04-08 00:00:00", is_female: false, activation_digest: nil, activated: false, activated_at: nil, reset_digest: nil, reset_sent_at: nil>
>> newmaleuser.save
   (41.6ms)  begin transaction
  User Exists (104.7ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('male@example.com') LIMIT 1
   (0.5ms)  rollback transaction
=> false

能够拯救女性用户

>> newfemaleuser = User.new(name: "Example female User", email: "female@example.com", password: "foobar", password_confirmation: "foobar", date_of_birth: "08/04/1987", is_female: "1")
=> #<User id: nil, name: "Example female User", email: "female@example.com", created_at: nil, updated_at: nil, password_digest: "$2a$10$NDDXC8n5iYAGEWD8VM8efOvM8UdGlj4iwIE/3Knd0vY...", remember_digest: nil, admin: false, date_of_birth: "1987-04-08 00:00:00", is_female: true, activation_digest: nil, activated: false, activated_at: nil, reset_digest: nil, reset_sent_at: nil>
>> newfemaleuser.save
   (0.3ms)  begin transaction
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('female@example.com') LIMIT 1
  SQL (71.2ms)  INSERT INTO "users" ("activation_digest", "created_at", "date_of_birth", "email", "is_female", "name", "password_digest", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["activation_digest", "$2a$10$T1dkwRJET0HPuyfu1XMFrearJSoo9c/2fC7UlZZMdgTWQkDUxTb2y"], ["created_at", "2014-10-30 15:58:17.963568"], ["date_of_birth", "1987-04-08 00:00:00.000000"], ["email", "female@example.com"], ["is_female", "t"], ["name", "Example female User"], ["password_digest", "$2a$10$NDDXC8n5iYAGEWD8VM8efOvM8UdGlj4iwIE/3Knd0vY1oYa.bChWK"], ["updated_at", "2014-10-30 15:58:17.963568"]]
   (107.1ms)  commit transaction
=> true
>> 

is_female:“1” is_female:“true”正在运作
我不知道为什么 is_female:“0”和is_female:“false”不起作用?

请帮助。

2 个答案:

答案 0 :(得分:1)

由于性别是一个布尔字段,您应该使用

validates :is_female, presence: true, inclusion: { in: [true,false] }

答案 1 :(得分:0)

我找到了。 存在:在

中为真
validates :is_female, presence: true, inclusion: { in: [true,false] }

造成了这个问题。 在O. Fernandez,K。Faustino&amp; Sons的&#34; The Rails 4 Way中找到以下内容。 V. Kushner&#34;

validates_inclusion_of :is_female, in: [true, false]

这很有效。 Yippie和所有测试都在通过。