【发布时间】:2011-12-15 21:51:56
【问题描述】:
我的模型中有一个validates inclusion:,但我认为“不包含在列表中”的默认错误消息完全没有用。
如何让它在错误消息本身中显示允许的选项列表? (例如,"is not one of the allowed options (option 1, option 2, or option 3)"?
更具体地说,让以下测试通过的最优雅的方法是什么:
describe Person do
describe 'validation' do
describe 'highest_degree' do
# Note: Uses matchers from shoulda gem
it { should allow_value('High School'). for(:highest_degree) }
it { should allow_value('Associates'). for(:highest_degree) }
it { should allow_value('Bachelors'). for(:highest_degree) }
it { should allow_value('Masters'). for(:highest_degree) }
it { should allow_value('Doctorate'). for(:highest_degree) }
it { should_not allow_value('Elementary School'). for(:highest_degree).with_message('is not one of the allowed options (High School, Associates, Bachelors, Masters, or Doctorate)') }
it { should_not allow_value(nil). for(:highest_degree).with_message('is required') }
it { subject.valid?; subject.errors[:highest_degree].grep(/is not one of/).should be_empty }
end
end
end
,给定以下模型:
class Person
DegreeOptions = ['High School', 'Associates', 'Bachelors', 'Masters', 'Doctorate']
validates :highest_degree, inclusion: {in: DegreeOptions}, allow_blank: true, presence: true
end
?
这是我目前在 config/locales/en.yml 中的内容:
en:
activerecord:
errors:
messages:
blank: "is required"
inclusion: "is not one of the allowed options (%{in})"
【问题讨论】:
标签: ruby-on-rails ruby validation internationalization interpolation