我希望确保我的类的
这会导致
理想情况下,一个空的URL应该只会产生一个错误(即“不能为空”)。因此,我已经修改了验证规则:
url
属性有一个值,如果有,它是有效的:class Entity < ActiveRecord::Base
validates :name, presence: true
validates :url, presence: true, :format => {:with => URI.regexp}
end
在Rails控制台中:
> e = Entity.new(name: 'foo')
=> #<Entity id: nil, name: "foo", url: nil, created_at: nil, updated_at: nil>
这会导致
url
属性出现两个错误:> e.valid?
=> false
> e.errors
=> #<ActiveModel::Errors:0x007fed9e324e28 @base=#<Entity id: nil, name: "foo", url: nil, created_at: nil, updated_at: nil>, @messages={:url=>["can't be blank", "is invalid"]}>
理想情况下,一个空的URL应该只会产生一个错误(即“不能为空”)。因此,我已经修改了验证规则:
validates :url, presence: true, :with => Proc.new { URI.regexp if :url? }
然而,我无法使语法正常工作。我缺少什么?
present?
时,它是否有效?validates :url, presence: true, :with => Proc.new { URI.regexp if :url.present? }
- Pavanvalidates :url, presence: true
和validates_format_of :url, with:=> URI.regexp, if: "url.present?"
。 - Pavan