Note that there are some explanatory texts on larger screens.

plurals
  1. PORails, custom validation and error not showing up
    primarykey
    data
    text
    <p>I've currently five boolean attributes. I do a custom validation on them : </p> <pre><code>def limit_impacts i = 0 choices = [self.first_attr, self.sec_attr, self.third_attr, self.fourth_attr, self.fifth_attr] choices.each do |choice| if choice == true i+=1 end end if i &gt; 2 errors[:base] &lt;&lt; ("There must be one or two impacts.") end end </code></pre> <p>The idea is to test if more than two of them are set to true, if it's the case, set an error. I'm setting a <code>:base error</code> because it's not related directly to only one attribute.</p> <p>I'm simply doing this for my validation : <code>validate :limit_impacts</code></p> <p>and the part of the view handling this : </p> <pre><code> = f.input :first_attr, :as =&gt; :boolean = f.input :sec_attr, :as =&gt; :boolean = f.input :third_attr, :as =&gt; :boolean = f.input :fouth_attr, :as =&gt; :boolean = f.input :fifth_attr, :as =&gt; :boolean </code></pre> <p>The problem is, when I check more than 2 checkboxes the entrie is not saving and that's normal, but no error message is showing up in the view.</p> <p>What am I doing wrong ?</p> <p>By the way I tested it in rails console :</p> <pre><code>MyModel.errors[:base] =&gt; ["There must be one or two impacts."] </code></pre> <p>And this syntax doesn't work either :</p> <pre><code>errors.add :base, "message" </code></pre> <p>EDIT : Here's my controller. It's about the edit method.</p> <pre><code> def edit @page_title = t('projects.edit.title') @project = Project.find(params[:id]) @steps = @project.steps @rewards = @project.rewards @project_bearer = @project.user end </code></pre> <p>Nothing linked with these attributes.</p> <p>When I try to create a project via the rails console, it returns me false :</p> <pre><code>2.0.0p247 :001 &gt; t = Project.create(:social_influence =&gt; true, :environmental_influence =&gt; true, :economical_influence =&gt; true) =&gt; &lt;Project all my attributes ..&gt; 2.0.0p247 :002 &gt; t.save (1.2ms) BEGIN (2.0ms) ROLLBACK =&gt; false </code></pre> <p><strong>SOLUTION :</strong></p> <p>The problem was my update method, bewteen render and redirect. Thanks to @delba I solved it. If you want to see the solution, there's a discussion in the comments of his answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload