This blog is part of our Rails 5 series.
Active Record validations by default provides an error messages, based on applied attributes. But some time we need to display a custom error message while validating a record.
We can give custom error message by passing String or Proc to :message.
1 2class Book < ActiveRecord::Base 3 # error message with a string 4 validates_presence_of :title, message: 'You must provide the title of book.' 5 6 # error message with a proc 7 validates_presence_of :price, 8 :message => Proc.new { |error, attributes| 9 "#{attributes[:key]} cannot be blank." 10 } 11end 12
What's new in Rails 5 ?
Rails 5 allows passing record to error message generator. Now we can pass current record object in a proc as an argument, so that we can write custom error message based on current object.
Revised example with current record object.
1 2class Book < ActiveRecord::Base 3 # error message with simple string 4 validates_presence_of :title, message: 'You must provide the title of book.' 5 6 # error message with proc using current record object 7 validates_presence_of :price, 8 :message => Proc.new { |book, data| 9 "You must provide #{data[:attribute]} for #{book.title}" 10 } 11end 12