我有一些命名空間模型,它們之間的關系如下:
my_ns/main.rb
module MyNs
class Main < ApplicationRecord
has_many :secondary
accepts_nested_attributes_for :secondary, allow_destroy: true
end
end
my_ns/secondary.rb
module MyNs
class Secondary < ApplicationRecord
belongs_to :main
has_many :tertiary
accepts_nested_attributes_for :tertiary, allow_destroy: true
end
end
namespace/tertiary.rb
module MyNs
class Tertiary < ApplicationRecord
belongs_to :secondary
validate :custom_method
private
def custom_method
errors.add(:thing, :custom_method_translation) if # condition
end
end
end
然后我有一個表單,可以讓我添加一個main、多個secondary和tertiary實體。這一切都很好,直到我嘗試驗證custom_method。當驗證失敗并被errors.add(:thing, ...)觸發時,驗證訊息顯示如下:
二級三級東西是無效的。
基本上,我想說“Tertiary 的東西是無效的”。我看過這個 Stackoverflow 的答案,它暗示使用ActiveRecord 的i18n
config/locales/en.yml:
en:
activerecord:
attributes:
main_model/nested_model:
key: 'Key'
問題是,我的模型嵌套了 1 層以上,并且有命名空間。我試過這樣的事情:
en:
activerecord:
attributes:
my_ns/main/secondary/tertiary:
thing: 'Thing'
# OR
en:
activerecord:
attributes:
my_ns/main/my_ns/secondary/my_ns/tertiary:
thing: 'Thing'
# OR
en:
activerecord:
attributes:
my_ns/main:
my_ns/secondary:
my_ns/tertiary:
thing: 'Thing'
沒有任何效果......錯誤訊息仍然顯示為“次要第三項無效”。
有誰知道如何使用嵌套的命名空間模型來處理這個問題?這是可以處理的嗎?或者,如果有辦法阻止 Rails 嘗試預先添加模型鏈,那也可以。我只需要錯誤說“事物無效”,或“三級的事物無效”等。我不想看到“中學三級......”
uj5u.com熱心網友回復:
您可以檢查此問題https://github.com/rails/rails/issues/19863它看起來與您的相似。
不要從頂級模型添加完整的鏈,而是嘗試直接從secondary模型添加
en:
activerecord:
attributes:
secondary/tertiary:
thing: 'Thing'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/514395.html
上一篇:如何在選擇中排除選項的第一個值
下一篇:自定義驗證或擴展驗證
