我正在学习Michael Hartl的Ruby on Rails教程,并且我一直在考验。这是我在控制台中的测试:
root@sample_app# rails console
Loading development environment (Rails 4.2.0)
user = User.new(name: "", email: "mhartl@example.com")
#=> #<User id: nil, name: "", email: "mhartl@example.com", created_at: nil, updated_at: nil>
user.valid?
#=> true
user = User.new(name: "Example User", email: "mhartl@example.com")
#=> #<User id: nil, name: "Example User", email: "mhartl@example.com", created_at: nil, updated_at: nil>
user.valid?
#=> true
无论名称是什么,user.valid?
始终返回true
。有谁知道为什么?
答案 0 :(得分:4)
除非你告诉它需要应用一些验证,否则它会假设有一个空名称是正确的。
此示例的验证示例如下:
validates :name, presence: true, allow_blank: false
您可以阅读有关验证here
的信息答案 1 :(得分:0)
原因是:在rails控制台中,我需要输入验证。
root@sample_app# rails console --sandbox
Loading development environment in sandbox (Rails 4.2.0)
Any modifications you make will be rolled back on exit
>> class User < ActiveRecord::Base
>> validates(:name, presence: true)
>> end
=> {:presence=>true}
>> user = User.new(name: "", email: "mhartl@example.com")
=> #<User id: nil, name: "", email: "mhartl@example.com", created_at: nil, updated_at: nil>
>> user.valid?
=> false
>> user = User.new(name: "Example User", email: "mhartl@example.com")
=> #<User id: nil, name: "Example User", email: "mhartl@example.com", created_at: nil, updated_at: nil>
>> user.valid?
=> true
>>