簡體   English   中英

檢查 attribute_changed 了嗎? 在 ActiveModel::EachValidator 中

[英]Checking if attribute_changed? in ActiveModel::EachValidator

我有一個 class 人,他有名字、中間名、姓氏。 我有一個自定義的 Each 驗證器,用於這 3 個屬性,就像這樣

validates :first_name, :middle_name, :last_name, nameValidator: true

在此驗證器中,我想檢查這 3 個屬性中的任何一個是否已更改,並在給定更多條件后驗證名稱。 為此,我正在嘗試 attribute_changed? 但它不起作用。

我已經檢查了 ActiveModel::Dirty 和 Activerecod::Dirty 的不同方法,但似乎無法檢查每個屬性的更改。 我錯過了什么?

module Person
  class nameValidator < ActiveModel::EachValidator

    def validate_each(record, attribute, value)
      return unless can_normalize?(record)
      #Normalization code 
    end

   def can_normalize?(record)
      anything_new = record.new_record? || attribute_changed?
   end
  end
end

如果您需要檢查某些屬性是否已更改,您需要調用attribute_changed? 記錄上的方法並像這樣傳遞此屬性

return unless record.new_record? || record.attribute_changed?(attribute)

或者可以使用這樣的元編程方法

return unless record.new_record? || record.public_send("#{attribute}_changed?")

一些注意事項:

在 Ruby 中,我們通常對 class 名稱使用 PascalCase,對 hash 密鑰使用 snake_case

驗證用於數據驗證,而不是用於某些規范化。 它通常用於添加驗證錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM