【问题标题】:Expect `valid?` to return `false`, but always got `true`期望 `valid?` 返回 `false`,但总是得到 `true`
【发布时间】:2015-03-05 04:57:42
【问题描述】:

我正在学习 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。有人知道为什么吗?

【问题讨论】:

  • 您能否提供您对name 字段的验证?

标签: ruby-on-rails ruby ruby-on-rails-3 validation


【解决方案1】:

除非你告诉它需要应用一些验证,否则它会假设有一个空名称是可以的。

此示例的验证示例如下:

validates :name, presence: true, allow_blank: false

您可以阅读有关验证的信息here

【讨论】:

  • , allow_blank: false 添加到该验证中应该会得到大卫之后的行为。
  • 感谢您的回复。根据您的提示,我找到了原因:在 Rails 控制台中,我需要编写验证。所以,
【解决方案2】:

原因是:在 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
>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多