I have a form that students are using to rank 6 classes from 1 to 6. If they select Math as “1” (the hardest), then I don’t want them to be able to select another subject as the hardest. The form will obviously give them the option to select “1” for each subject, but I want to use validations to protect against submission of a form that doesn’t follow instructions
This is a snippet from the form
<div class="field">
<%= f.label(:math, "Mathp") %>
<%= f.select:math, 1..6 %> </br>
</div>
<div class="field">
<%= f.label(:french, "French") %>
<%= f.select:french, 1..6 %> </br>
</div>
I was going to use a validation method like this, but I don’t think the logic of it works (i.e. it doesn’t guard against every possible situation) and it’s probably shitty (non-functional) code too, because i’m just learning how to code (actually I’ve been failing at it for quite a while now). Can you suggest improvements?
validates :rank_favorites
...
def rank_favorites
unless :math != :french && :french != :history && :history != :spanish && :spanish != :art && :art != :physed return false
end
Your
rank_favoritesis, sadly, way off but ignorance can be fixed through learning. You’re just comparing a bunch of symbols and that doesn’t do anything useful (at least not as far as you’re concerned), you’re validator reduces to this:which is equivalent to:
You probably want to use
validate :rank_favorites(notvalidates) and your validator would add error messages instead of simply return a boolean:The
Array#uniqmethod will produce a copy of your array with the duplicates removed, if the lengths don’t match then something was removed and you had duplicate entries.You might want to spend some time reading the validations guide: