Rails-查找或创建-是否存在查找或构建?


68

我目前正在使用:

XXX.find_or_create_by_uuid(XXXX)

有没有办法找到或建立?

Answers:


99

尝试 XXX.find_or_initialize_by_uuid(XXXX)


注意:您不能像使用bang!运算符find_or_initialize_by那样使用bang运算符find_or_create_by。这是因为如果在保存对象时遇到麻烦,便会使用bang引发异常,而这种初始化仅在初始化时不适用。
约书亚·品特


-2

如果您想自己制作(路线5):

class ApplicationRecord < ActiveRecord::Base

  def self.find_or_build_by hash
    result = all.where(hash)
    result.present? ? result : none.build(hash)
  end
end

6
请不要这样做。习惯于该标准的其他开发人员find_or_initialize_by会对此感到困惑,更糟糕的是,您会因此而判断。
约书亚·品特
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.