Kyle Macey
Kyle Macey

Reputation: 8154

Validate only when

I need to validate a value's presence, but only AFTER the value is populated. When a User is created, it is not required to set a shortcut_url. However, once the user decides to pick a shorcut_url, they cannot remove it, it must be unique, it must exist.

If I use validates_presence_of, since the shortcut_url is not defined, the User isn't created. If I use :allowblank => true, Users can then have "" as a shortcut_url, which doesn't follow the logic of the site.

Any help would be greatly appreciated.

Upvotes: 0

Views: 320

Answers (3)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Here we are always making sure the shortcut_url is unique, but we only make sure it is present if the attribute shortcut_selected is set (or if it was set and now was changed)

class Account 
  validates_uniqueness_of :shortcut_url
  with_options :if => lambda { |o| !o.new_record? or o.shortcut_changed? } do |on_required|
    on_required.validates_presence_of :shortcut_url
  end

end

You'll need to test to make sure this works well with new records.

Upvotes: 1

Gal
Gal

Reputation: 5907

try conditional validations, something like:

validates_presence_of :shortcut_url, :if => :shortcut_url_already_exists?
validates_uniqueness_of :shortcut_url, :if => :shortcut_url_already_exists?

def shortcut_url_already_exists?
  @shortcut_url_already_exists ||= User.find(self.id).shortcut_url.present?
end

Upvotes: 0

PreciousBodilyFluids
PreciousBodilyFluids

Reputation: 12011

Try the :allow_nil option instead of :allow_blank. That'll prevent empty strings from validating.

Edit: Is an empty string being assigned to the shortcut_url when the user is being created, then? Maybe try:

class User < ActiveRecord::Base
  validates_presence_of :shortcut_url, :allow_nil => true

  def shortcut_url=(value)
    super(value.presence)
  end
end

Upvotes: 0

Related Questions