【问题标题】:Rails model validation failing and it shouldn'tRails 模型验证失败,它不应该
【发布时间】:2014-05-14 00:04:39
【问题描述】:

我的模型上有以下内容:

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 已经被 采取)

有什么想法吗?

【问题讨论】:

    标签: ruby ruby-on-rails-3 validation validates-uniqueness-of


    【解决方案1】:

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

    【讨论】:

    • temp_woeid 是实际 woeid 值的副本。但是,您可以看到 handle_woeid_issue 从未以某种方式被调用。那怎么会是问题呢?
    • @content01 你是对的,虽然我有另一个怀疑。查看我的编辑。
    • 编辑有意义。但是,Place 似乎也有一个 woeid 字段。当他们执行gp.attributes.dup 时,Place 对象的woeid 就在该哈希中。他们从不删除它,所以当他们create! 时它应该存在以供验证。我不确定回调是否最终是问题所在。
    • 使用 before_validation 而不是 before_create 实际上解决了我的问题。非常感谢!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      相关资源
      最近更新 更多