0
我有2個名爲Drug and Frequency的模型。find_or_create_by與自定義ActiveModel :: Validator一起使用失敗
#app/models/frequency.rb
class Frequency
validates :code, presence: true
end
#app/models/drug.rb
class DrugValidator < ActiveModel::Validator
def validate(record)
drug_attributes = {name: record.name}
if Drug.where(name: record.name).any?
record.errors[:base] << "The drug #{record.name} already exists in system."
end
end
end
class Drug
validates_with DrugValidator, if: (lambda {|drug| drug.name.present?})
end
> pf = Frequency.find_or_create_by(code: 'Q24')
Frequency Load (0.4ms) SELECT "frequencies".* FROM "frequencies" WHERE "frequencies"."code" = $1 LIMIT 1 [["code", "Q24"]]
=> #<Frequency id: 7, code: "Q24", created_at: "2015-11-02 03:41:34", updated_at: "2015-11-02 03:41:34">
> pf.persisted?
=> true
> pf.valid?
=> true
> pf.new_record?
=> false
> pd = Drug.find_or_create_by(name: 'SomeDrug', unit: 'tablet')
=> #<Drug id: 10, name: "SomeDrug", created_at: "2015-11-05 07:42:46", updated_at: "2015-11-05 07:42:46", unit: "tablet">
> pd.persisted?
=> true
> pd.new_record?
=> false
> pd.valid?
=> false
> pd.errors.messages
=> {:base=>["The drug SomeDrug already exists in system."]}
即使從系統獲取記錄時,也會執行自定義DrugValidator。我如何避免這種find_or_create_by?