ruby-on-railsvalidationinclusion

rails validate specific value


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"

Solution

  • 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?