10

I have this code

I have these options and if the user select anything except 'British Columbia' to give him error message that the province have to 'British Columbia'

I believe it will solve by using the model validation

<%= f.label :province ,"Province (required)"%><br>
    <%= f.select(:province, [["Select One", ""],'Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Northwest Territories','Nunavut','Ontario','Prince Edward Island','Quebec','Saskatchewan','Yukon'], {}) %>

User.rb

  validates :province, presence: "British Columbia"
nourza
  • 2,215
  • 2
  • 16
  • 42
  • I had the same problem last week. As mentioned above you've used the wrong validation type. I found this article useful. https://guides.rubyonrails.org/active_record_validations.html#inclusion I hope it helps. – Ben Strachan Oct 13 '18 at 00:17

1 Answers1

15

You shouldn't use presence, it's the wrong validation. You should use inclusion:

validates :province, inclusion: { in: %w[British Columbia] }

You realize this is a nonsensical problem, right? What's the point of offering several alternatives in the view if the validation will only accept one?

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
John Feltz
  • 550
  • 3
  • 9