rubyruby-on-rails-3validationvalidates-uniqueness-of

Rails model validation failing and it shouldn't


I have the following on my model:

validates_uniqueness_of :woeid

before_create :handle_woeid_issue

def handle_woeid_issue
    Rails.logger.info 'DID ENTER HERE'  #never enters here for some reason
    self.woeid = self.temp_woeid
  end

def self.create_if_not_existing(woeid)
    unless Location.find_by_woeid(woeid)
      Rails.logger.info '>>>> ' + Location.find_by_woeid(woeid).inspect #THIS OUTPUTS NIL
      gp = Place.find_by_woeid(woeid)
      Location.from_place(gp)
    end
  end

def self.from_place(gp)
    raise "Invalid argument " if geoplanet_place.nil?
    attrs = gp.attributes.dup
    attrs['temp_woeid'] = attrs['woeid']
    Rails.logger.info '>>>>>>>>>>>>> ' + Location.where(:woeid => attrs['woeid']).inspect #STILL NIL
    location = self.create!(attrs)
    location
  end

If the whole thing starts from

Location.create_if_not_existing(woeid)

and it is being NIL (so no other record have the same woeid) WHY IT IS GIVING ME:

ActiveRecord::RecordInvalid (Validation failed: Woeid has already been taken)

Any ideas?


Solution

  • This is the order of execution during the insertion of an ActiveRecord object:

    (-) save
    (-) valid
    (1) before_validation
    (-) validate            *** BOOM
    (2) after_validation
    (3) before_save         *** too late
    (4) before_create
    (-) create
    (5) after_create
    (6) after_save
    (7) after_commit
    

    This means the validation is indeed run before your callback is called. To prevent this issue, you can use before_validation instead of before_create

    Source: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html