我正在尝试在类上使用验证器,以验证API上的信息。但是,当我调用有效时,它总是返回true?
你知道为什么吗?我正在使用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)
答案 0 :(得分:0)
我无法使用Rails 4.2.10复制它。也许您需要升级到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)"]}>