我在我的模型中有一个validates inclusion:
,但我认为“不包含在列表中”的默认错误消息完全没有用处。如何为validates_inclusion_of显示允许的选项列表的错误消息?
如何让它显示错误消息中允许的选项列表本身? (例如,"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
这是我在我的配置/ locales/en.yml目前:
en:
activerecord:
errors:
messages:
blank: "is required"
inclusion: "is not one of the allowed options (%{in})"
我很惊讶没有人对此评论过。干得不错!我认为这是一段很棒的代码。 :+1: – 2014-02-11 21:45:16