Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default validation error messages on belongs_to field

In Rails 5, belongs_to relation becomes required as default and gives Model must exist message on every failed validation. I want to localize default messages on every belongs_to occurrence at once. For example ...

In my model:

class Person < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :person
  validates :author_date, presence: true
end

In my localization file:

en:
     activerecord:
       errors:
         blank: "can't be blank" # not showing on book.errors[:person]

In console:

book = Book.new
book.save
puts book.errors.to_json
>> {person: ["must exist"], :author_date: ["can't be blank"]}

How can I localize must exist messages in YML file.

like image 327
Буянбат Чойжилсүрэн Avatar asked Oct 28 '25 04:10

Буянбат Чойжилсүрэн


1 Answers

It has key required, try:

en:
  activerecord:
    errors:
      messages:
        required: "custom required message"
like image 54
Thanh Avatar answered Oct 29 '25 17:10

Thanh



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!