为什么 false 使 validates_presence_of 无效? [英] Why does false invalidate validates_presence_of?
问题描述
好的步骤来重现这个:
prompt> rails test_app
prompt> cd test_app
prompt> script/generate model event_service published:boolean
然后进入迁移并添加not null并默认发布为false:
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
此时您应该没有错误.现在编辑模型,以便您 validate_presence_of 已发布:
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
现在编辑单元测试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
并运行耙子:
prompt>rake
您将在测试中遇到错误.现在将 e.published 设置为 true 并重新运行测试.有用!我认为这可能与布尔字段有关,但我无法弄清楚.这是rails中的错误吗?还是我做错了什么?
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?
推荐答案
请参阅 API 文档...
如果您想验证布尔字段的存在(其中实际值为真和假),您将需要使用 validates_inclusion_of :field_name, :in => [true, false].
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].
这篇关于为什么 false 使 validates_presence_of 无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!