Don't miss

I created an open source development tool to quickly & dynamically mock API endpoints. Check it out at GitHub: DuckRails

Heads up

I will no longer maintain arubystory. For new posts, find me at my personal blog. CU there!

Saturday, February 14, 2015

Radio buttons & required boolean attributes

Lately, I was trying to create a form for one of my models which had a required boolean attribute.

The model

class Foo < ActiveRecord::Base

  validates_presence_of :a_flag

end

The form

<h1>Foos#new</h1>

<%= form_for @foo do |form| %>
    <% if @foo.errors %>
        <% @foo.errors.full_messages.each do |message| %>
            <%= message %>
            <br />
        <% end %>
    <% end %>
    <table>
        <tr>
            <td><%= form.label 'a_flag_true', 'Yes' %></td>
            <td><%= form.radio_button :a_flag, true %></td>
        </tr>

        <tr>
            <td><%= form.label 'a_flag_false', 'No' %></td>
            <td><%= form.radio_button :a_flag, false %></td>
        </tr>
    </table>

    <%= form.submit 'Answer' %>
<% end %>
So far so good.
Back to the browser now, everything seemed fine till the moment I tried to submit the No value.




I was like this:

I googled around to find some answers on this and some suggested that I should use the inclusion validator. And so I did.

The updated model

class Foo < ActiveRecord::Base

  validates :a_flag,
            :inclusion => { :in => [true, false] }

end

Back to the browser everything seemed fine. I could submit both Yes and No values but there was a problem when I was trying to submit the form without selecting a value.

The error message was not quite what I wanted... And for sure, I wanted to find a solution that won't make me override default error messages. 
After a while doing this:

the idea came to me.

What if I forced the presence validation only when the value was nil?


The model

class Foo < ActiveRecord::Base

  validates :a_flag,
            :presence => { :if => 'a_flag.nil?' }

end

I could now submit both values and the desired message was showing up if no selection was made.
Done. Problem solved.


Post a Comment