0

我的模型上有以下内容:

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(所以没有其他记录具有相同的 woeid)为什么它给了我:

ActiveRecord::RecordInvalid(验证失败:Woeid 已被占用)

有任何想法吗?

4

2 回答 2

2

这是插入 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

于 2014-05-14T00:12:29.220 回答
0

使用before_savebefore_vaidate回调而不是before_create尝试

于 2014-10-11T11:43:33.647 回答