简体   繁体   English

Ruby on Rails 4:有效吗? 总是返回true

[英]Ruby on Rails 4: valid? always returns true

I'm trying to use validators on my class, to validate information on my API. 我正在尝试在类上使用验证器,以验证API上的信息。 But it always returns true, when I call valid? 但是它总是返回true,当我调用有效吗?

Do you have any idea why? 你知道为什么吗? I'm using Rails 4. 我正在使用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. 我无法使用Rails 4.2.10重现此内容。 Maybe you need to upgrade to Rails 4.2.latest??? 也许您需要升级到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)"]}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM