Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - Translating errors from nested model

pt-BR.yml:

pt-BR:
  activerecord:
    models:
      user: Usuário
      project: Projeto
    attributes:
      user:
        name: O nome
        description: A descrição
        projects: Os projetos
      project:
        name: O nome
  errors:
    format: "%{attribute} %{message}"
    messages:
      accepted: deve ser aceito
      blank: não pode ficar em branco
      ........

Models:

class User < ApplicationRecord
  has_many :projects, dependent: :destroy, inverse_of: :user

  accepts_nested_attributes_for :projects, allow_destroy: true
end

class Project < ApplicationRecord
  belongs_to :user, inverse_of: :projects

  validates :name, presence: true, length: { mininum: 3, maximum: 255 }
end

Controller:

def update
  if @user.update(user_params)
    render json: @user
  else
    render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity
  end
end

All the error messages are being translated when the method .error.full_messages is called, except those that comes from projects objects (as you may have notice above, I'm using accepts_nested_attributes_for).

I'm always receiving the following error message:

{
  "errors": [
     "Projects name deve conter no mínimo 3 caracteres"
  ]      
}

How can I translate Projects and name in my translation file or even remove the "Projects %atribute%" from the error messages (without any hack)?

like image 989
dev_054 Avatar asked Mar 09 '26 23:03

dev_054


1 Answers

For Rails 5.2 I had to check the core code to find out that it uses namespaces in the nested attribute's translation, like this:

  pt-BR:
    activerecord:
      attributes:
        user/projects:
          name: O nome de um projeto

So inside 'user/projects' node is where you can list the attributes of a Project nested in User.

like image 106
Victor BV Avatar answered Mar 11 '26 13:03

Victor BV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!