Rails 模型验证失败,不应该



我的模型上有以下内容:

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

如果整件事从

开始

Location.create_if_not_existing (woeid)

并且它是NIL(因此没有其他记录具有相同的woid)为什么它给我:

ActiveRecord::RecordInvalid(验证失败:woid已经存在)

任何想法?

这是在插入ActiveRecord对象期间的执行顺序:

(-) 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

这意味着验证确实在调用回调之前运行。为了防止这个问题,您可以使用before_validation而不是before_create

来源:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

使用before_savebefore_vaidate回调而不是before_create,并尝试

相关内容

  • 没有找到相关文章

最新更新