2

我有一個Message模型,其中content屬性(字符串)和sent屬性(boolean)。一個消息的content應該是可修改的,直到它被髮送,之後該字段應該變爲只讀。(其他屬性仍可修改,如message_opened)。Rails ActiveRecord有條件地保護屬性不被修改

我該如何做到這一點?我已經考慮覆蓋readonly?(僅適用於記錄級別),attr_readonly(不附條件)和驗證(不知道如何驗證content取決於其舊值和sent字段)。

回答

3

結果驗證是正確的方法:創建一個使用attribute_changed?(「屬性」是屬性的名稱,本例中爲「content」)和條件驗證的自定義驗證。

Message.rb:

validate_on_update :reject_modifying_content, if: :sent? 

def reject_modifying_content 
errors[:content] << "can not be changed!" if self.content_changed? 
end 

Rails 3 check if attribute changedSetting a field to read-only in Rails after it's createdhttp://api.rubyonrails.org/classes/ActiveModel/Dirty.html以獲取更多信息。

0

去了可能的答案,我想作爲設置領域:

attr_readonly 

是最好的選擇是將完全保護的那場沒有需要自定義代碼。

列爲readonly的屬性將用於創建新記錄,但 更新操作將忽略這些字段。