我在我的模型中有一個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