I have a few name-spaced Models, with relationships to each other as such:
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
I then have a form that lets me add a main
, multiple secondary
and tertiary
instances. This all works great, until I try to validate that custom_method
. When the validation fails, and errors.add(:thing, ...)
is triggered, the validation message appears as such:
Secondary tertiary thing is not valid.
Basically, I want this to say "Tertiary's thing is not valid." I've seen this Stackoverflow answer which alludes to using ActiveRecord's i18n
config/locales/en.yml
:
en:
activerecord:
attributes:
main_model/nested_model:
key: 'Key'
The thing is, my models are nested more than 1 level, and have namespaces. I've tried things like:
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'
And nothing has worked... The error message still appears as "Secondary tertiary thing is not valid".
Does anyone know how to handle this with nested, namespaced Models? Is this something that can be handled? Alternatively, if there's a way to stop Rails from attempting to prepend the Model chain, that would work too. I just need the error to say "Thing is invalid", or "Tertiary's thing is invalid", etc. I don't want to see "Secondary tertiary ..."
CodePudding user response:
You can check this issue https://github.com/rails/rails/issues/19863 it looks similar to yours.
Instead of adding complete chain from top model, try directly adding from the secondary
model
en:
activerecord:
attributes:
secondary/tertiary:
thing: 'Thing'