我的模型上有以下内容:
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已经存在 取)
有什么想法吗?
答案 0 :(得分: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
答案 1 :(得分:0)
使用before_save
或before_vaidate
回调代替before_create
并尝试