我在我的應用程序相當長的一段belongs_to的關聯,他們中的一些是可選的(即聯想可能是無),有些是強制性的(協會必須是有效的父記錄。爲belongs_to的關聯設定驗證錯誤消息變得容易
我最初的做法是用我自己的驗證方法來驗證給定的ID(這裏的強制性協會)
belongs_to :category
validates :category_id,
presence: true
validate given_category_exists
def given_category_exists
if category_id.present?
errors.add(:category_id, 'must be present') \
Category.exists?(category_id)
end
end
然後我發現的Rails會爲我做,如果我會用存在支票上的關聯所以我可以省略我自己的驗證方法:
belongs_to :category
validates :category,
presence: true
但現在,生成的錯誤消息將簡單地陳述爲:Category can't be blank
。這裏的問題是:(1)我可以提供更有用的信息嗎? (2)如何爲屬性插入我自己的翻譯? Category
是由驗證方法生成的默認標籤,can't be blank
是以下內容的默認錯誤文本:空白。
此問題的另一個問題:表單中的相關輸入字段未標記爲'field_with_errors',因爲此字段使用屬性名稱標識,而不是關聯名稱。
使用做事的標準的方式,我會額外的屬性添加到我的I18n翻譯文件的關聯category
的名稱,並增加了對標準信息的替代品:
en:
activerecord:
models:
attributes:
my_model:
category_id: 'This Category'
category: 'This Category'
errors:
models:
my_model:
attributes:
category:
blank: 'must be specified.'
很多線,其中的事情可能會出錯。我不喜歡這個想法添加表面屬性,這些表面屬性實際上不是屬性,而是關聯的名稱。
有沒有更簡單的方法?
不,您可能使用最簡單的方法來防止後來的麻煩。 – Supernini