Rails 将第二个字段名称添加到验证错误消息中
Rails add a second field name to validation error message
rails 5.2
, ruby 2.6.4
一条 Student
记录有这些字段,部分是:
fname,
lname,
emplid,
class_code,
...
class_code是数字1,2,3,4。
1 = freshman
2 = sophomore
3 = junior
4 = senior
我有一个验证:
validates_inclusion_of :class_code, :in => Constants::CLASS_CODES,
message: "The class code, %{value}, is not considered a valid class code."
这行得通,但如果我能知道发生此错误的学生记录,那将非常有帮助。我想将字段 emplid
添加到错误消息中。这可能吗?
类似于:
message: "For student {emplid}, %{value} is not considered a valid class code."
感谢任何提示。
您可以将 lambda 传递给 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." }
rails 5.2
, ruby 2.6.4
一条 Student
记录有这些字段,部分是:
fname,
lname,
emplid,
class_code,
...
class_code是数字1,2,3,4。
1 = freshman
2 = sophomore
3 = junior
4 = senior
我有一个验证:
validates_inclusion_of :class_code, :in => Constants::CLASS_CODES,
message: "The class code, %{value}, is not considered a valid class code."
这行得通,但如果我能知道发生此错误的学生记录,那将非常有帮助。我想将字段 emplid
添加到错误消息中。这可能吗?
类似于:
message: "For student {emplid}, %{value} is not considered a valid class code."
感谢任何提示。
您可以将 lambda 传递给 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." }