ActiveRecord checks URL if present

I would like to make sure that my class has a urlproperty, and if so, it really is:

class Entity < ActiveRecord::Base

  validates :name, presence: true
  validates :url, presence: true, :format => {:with => URI.regexp}

end

In the rails console:

> e = Entity.new(name: 'foo')
=> #<Entity id: nil, name: "foo", url: nil, created_at: nil, updated_at: nil> 

This results in two errors for the attribute 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"]}> 

Ideally, a nil urlwill create a single error (i.e. can't be blank).

So I changed the rule validates:

validates :url, presence: true, :with => Proc.new { URI.regexp if :url? }

I cannot get the syntax to work. What am I missing?

+4
source share
2 answers

Separate the two validators.

validates :url, presence: true
validates :url, format: { with: URI.regexp }, if: Proc.new { |a| a.url.present? }

(almost) 2 year anniversary edit

Like vrybas and state Barry, Proc is not needed. You can write your validators as follows:

validates :url, presence: true
validates :url, format: { with: URI.regexp }, if: 'url.present?'
+17

, , Proc.

, format, nil, allow_nil,

allow_blank , '', , url .

:

validates :url, presence: true
validates :url, format: { with: URI.regexp }, allow_blank: true
+5

Source: https://habr.com/ru/post/1547788/


All Articles