Published on Oct 14, 2014
in category programming
Lately, I was trying to create a form for one of my models which had a required boolean attribute.
class Foo < ActiveRecord::Base
validates_presence_of :a_flag
end
<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.
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?
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.