Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

ruby - how to customize rails activerecord validation error message to show attribute value

When a user tries to create a record with a name that already exists, I want to show an error message like:

name "some name" has already been taken

I have been trying to do:

validates_uniqueness_of :name, :message => "#{name} has already been taken"

but this outputs the table name instead of the value of the name attribute

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

2 things:

  1. The validation messages use the Rails I18n style interpolation, which is %{value}
  2. The key is value rather than name, because in the context of internationalization, you don't really care about the rest of the model.

So your code should be:

validates_uniqueness_of :name, :message => '%{value} has already been taken'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...