Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

ruby on rails - Why does false invalidate validates_presence_of?

Ok steps to reproduce this:

prompt> rails test_app
prompt> cd test_app
prompt> script/generate model event_service published:boolean

then go into the migration and add not null and default published to false:

class CreateEventServices < ActiveRecord::Migration
  def self.up
    create_table :event_services do |t|
      t.boolean :published, :null => false, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :event_services
  end
end

now migrate your changes and run your tests:

prompt>rake db:migrate
prompt>rake

You should get no errors at this time. Now edit the model so that you validate_presence_of published:

class EventService < ActiveRecord::Base
  validates_presence_of :published
end

Now edit the unit test event_service_test.rb:

require 'test_helper'

class EventServiceTest < ActiveSupport::TestCase
  test "the truth" do
    e = EventService.new
    e.published = false
    assert e.valid?
  end
end

and run rake:

prompt>rake

You will get an error in the test. Now set e.published to true and rerun the test. IT WORKS! I think this probably has something to do with the field being boolean but I can't figure it out. Is this a bug in rails? or am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the API docs...

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...