gpt4 book ai didi

ruby-on-rails - 为什么 false 会使 validates_presence_of 无效?

转载 作者:行者123 更新时间:2023-12-03 05:53:38 26 4
gpt4 key购买 nike

重现此问题的正确步骤:

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

然后进入迁移并添加 not null 并默认发布为 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

现在迁移您的更改并运行测试:

prompt>rake db:migrate
prompt>rake

此时您应该不会收到任何错误。现在编辑模型以便您发布 validate_presence_of:

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

并运行 rake:

prompt>rake

您将在测试中收到错误。现在将 e.published 设置为 true 并重新运行测试。有用!我认为这可能与该字段为 bool 值有关,但我无法弄清楚。这是 Rails 中的错误吗?还是我做错了什么?

最佳答案

请参阅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].

关于ruby-on-rails - 为什么 false 会使 validates_presence_of 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2883823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com