简体   繁体   中英

Rails4 - How to validate Gender[boolean type] field of my webapp

I am new to rails and trying to add Gender to my existing application which I created using Michael Hartl's tutorials

I decided to use boolean type for Gender. I added the new columns in migration file

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

Ran the following to create tables with my new columns

$bundle exec rake db:migrate

Decided to create Select boxes because I couldn't create radio buttons after repeated attempts

app/models/user.rb

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

Updated the test test/models/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
.
.

This is Select box snippet from view of my Sign up form

app/views/users/new.html.erb

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

This is Select box snippet from HTML Signup form

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

Added following to be immune from mass assign vulnerability

app/controllers/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  
.
.

Logs from 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

Information from the debugger in browser

--- !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

I get the following when I try to signup

The form contains 1 error.

    Is female is not included in the list

I am not able to resolve this error. Kindly help

-- Update --

Thanks @user3243476 , I changed my validation as follows

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

I am able to create profile with gender as female

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

But I am not able to create profile with gender as male I get a new error

The form contains 1 error.

    Is female can't be blank

This is 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

Debugger log

--- !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

In rails console I tried the following

Not able to save male user

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

Able to save female user

>> 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 working
I don't know why
is_female: "0" and is_female: "false" doesn't work?

Kindly help.

由于性别是布尔字段,因此您应该使用

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

I found it. presence: true in

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

is causing the problem. Found the following in "The Rails 4 Way by O. Fernandez, K. Faustino & V. Kushner"

validates_inclusion_of :is_female, in: [true, false]

This is working. Yippie and all the tests are passing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM