简体   繁体   中英

Ruby on Rails 4: valid? always returns true

I'm trying to use validators on my class, to validate information on my API. But it always returns true, when I call valid?

Do you have any idea why? I'm using Rails 4.

class Address
   include ActiveModel::Model
   include ActiveModel::Validations
   include ActiveModel::AttributeMethods

   attr_accessor :street

   validates :street, length: { minimum: 10, maximum: 100 }
end

address = Address.new
address.street = 'aa'
address.valid? (returns true)

I can not reproduce this using Rails 4.2.10. Maybe you need to upgrade to Rails 4.2.latest???

Loading development environment (Rails 4.2.10)

Frame number: 0/5
[1] pry(main)> class Address
[1] pry(main)*   include ActiveModel::Model   
[1] pry(main)*   include ActiveModel::Validations   
[1] pry(main)*   include ActiveModel::AttributeMethods   
[1] pry(main)*   
[1] pry(main)*   attr_accessor :street   
[1] pry(main)*   
[1] pry(main)*   validates :street, length: { minimum: 10, maximum: 100 }   
[1] pry(main)* end  
=> {:length=>{:minimum=>10, :maximum=>100}}
[2] pry(main)> a = Address.new
=> #<Address:0x00007fb728c42b10>
[3] pry(main)> a.street = 'aa'
=> "aa"
[5] pry(main)> a.valid?
=> false
[6] pry(main)> a.errors
=> #<ActiveModel::Errors:0x00007fb728bafce8
 @base=#<Address:0x00007fb728c42b10 @errors=#<ActiveModel::Errors:0x00007fb728bafce8 ...>, @street="aa", @validation_context=nil>,
 @messages={:street=>["is too short (minimum is 10 characters)"]}>

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