Post outline

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 googled around to find some answers on this and some suggested that I should use the inclusion validator. And so did I.

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.

And then I thought, 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.

My news

I created an open source development tool named DuckRails for mocking API endpoints quickly and dynamically.

Version 2.1.2 is out and it is now possible to run the application via its docker image.

Star


Ruby does Gtk
I published a tutorial for creating a simple Linux Desktop app with Ruby.