I created a form (“Form1”) and a validation to go along with it. Then I created a different form (“Form2”) for another purpose but the validation method for “Form1” is being triggered when I submit Form2
Form2 and Form1 are both being submitted to the same database, but I didn’t think the validation would apply to both of them, because attribute/method names were different in the forms
Form 1
<%= form_for(@guess) do |f| %>
<% if @guess.errors.any? %>
<div class="field">
<%= f.label(:math, "I think many students will fail Math") %>
<%= f.check_box(:math) %> </br>
</div>
<div class="field">
<%= f.label(:french, "I think many students will fail French") %>
<%= f.check_box(:french) %> </br>
</div>
I do the same for 6 subjects. Students are required to select 3 subjects that might create fails..
Validation for Form1 in model Guess.rb
validates_inclusion_of :possible_assessment_failures, :in => 1..3, :message => "You must check off 1,2 or 3 different assessments for question 1"
...
def possible_assessment_failures
[math, french, english, science, history, geography].select{|x| x }.count
end
Comment: I assumed that this validation got triggered because the methods in the form (:french, :math etc) were in the array [math, french…] in the validation…I’m guessing that’s wrong
—
Form2
In the controller….
@teacher = Guess.new
in the view…
<div class="field">
<%= f.label(:MrSmith, "MrSmith") %>
<%= f.select:MrSmith, 1..6 %> </br>
</div>
So why is the validation for form1 getting called when I submit form2?
As mentioned, I thought the validation got called for form1 because the methods in the array in the validation (i.e. the names of the subjects
[math, french, english, science, history, geography].select{|x| x }.count
were named in the form
<%= f.check_box(:math) %>
so if my Form2 has different attributes (like teacher’s names
<%= f.select:MrSmith, 1..6 %>
I don’t understand why that would trigger a validation with the names of subjects (math, french etc) in it?
I’m assuming that’s totally wrong thinking on my part. So what triggers the validation and how do I get it not to apply on form2?
All of the validations in Guess.rb are called whenever the guess model is saved (by default, you can disable them with
save(:validate => false)).It’s not generally a good idea to only apply some validations when saving a model since you’ll lose the guarantee that your database is consistent with all of your validations.
If you really want to do it, you could create a new attribute and only run the validation if that attribute is true, see this answer https://stackoverflow.com/a/3956701/625365