John Cowan
John Cowan

Reputation: 1674

Rails add a second field name to validation error message

rails 5.2, ruby 2.6.4

A Student record has these fields, in part:

fname,
lname,
emplid,
class_code,
...

The class_code is a digit 1,2,3,4.

1 = freshman
2 = sophomore
3 = junior
4 = senior

I have a validation:

validates_inclusion_of :class_code, :in => Constants::CLASS_CODES,    
    message: "The class code, %{value}, is not considered a valid class code."

This works, but it would be very helpful if I could tell which student record this error happens on. I would like to add the field emplid to the error message. Is this possible?

Something like:

message: "For student {emplid}, %{value} is not considered a valid class code."

Thanks for any tips.

Upvotes: 1

Views: 55

Answers (1)

Yakov
Yakov

Reputation: 3201

You can pass a lambda to message.

validates_inclusion_of :class_code, :in => Constants::CLASS_CODES,
  message: ->(student, options) { "For student #{student.emplid}, #{options[:value]} is not considered a valid class code." }

Upvotes: 3

Related Questions