Rails validates_presence_of Strangeness
I found an annoying bug in validates_presence_of, it does not like booleans.
class CreateNodes < ActiveRecord::Migration
def self.up
create_table :nodes do |t|
t.column :boolean_var, :boolean, :default => 0
end
end
endclass Node < ActiveRecord::Base
validates_presence_of :boolean_var
endclass NodeTest < Test::Unit::TestCase
def test_boolean_var
node = Node.new
node.boolean_var = 0
node.save!
end
end 1) Error:
test_boolean_var(NodeTest):
ActiveRecord::RecordInvalid: Validation failed: Boolean var can't be blank
/opt/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/validations.rb:736:in
`save!'
/Users/jwulff/Development/NodeTestApp/test/unit/node_test.rb:5:in
`test_boolean_var'
1 tests, 0 assertions, 0 failures, 1 errorsBlake Watters gave me this workaround.
validates_inclusion_of :boolean_var, :in => [true, false]I’ve opened a ticket at dev.rubyonrails.org
UPDATE: The ticket has been closed as invalid. Manfred says:
validates_presence_of behaves exactly as documented. Please use {{{validates_inclusion_of :boolean_var, :in => [true, false]}} as the first commenter suggested.
Trackbacks
Use the following link to trackback from your own site:
http://www.johnwulff.com/trackbacks?article_id=rails-validates_presence_of-strangeness&day=15&month=05&year=2006
-
Imagine an application with simple Person and Article models. The Article model has a foreign key: person_id. In this application the best way to get the latest Article for a Person is: class Person < ActiveRecord::Base has_one :latest_article,...