title: Rails 3 - Validating Forms with Only One Set of Radio Buttons
body: <p>As a beginning Ruby on Rails 3 developer, I'm looking for recommendations on how best to validate a form with just one set of radio buttons. This particular form is part of a web app with multiple forms - my controller to direct the flow to different forms depending on the answer selected.</p>
  
  <p>My html.erb snippet:</p>
  
  <pre><code>&lt;%= form_for @selection do |f| %&gt;
  &lt;%= f.error_messages %&gt;
  &lt;div class="field"&gt;
    &lt;%= f.radio_button :answer, 'Y' %&gt;
    &lt;%= f.label :answer, 'Y' %&gt;
    &lt;br/&gt;
    &lt;%= f.radio_button :answer, 'N' %&gt;
    &lt;%= f.label :answer, 'N' %&gt;
  &lt;/div&gt;
  
  &lt;div class="action"&gt;
    &lt;%= submit_tag 'Save', :name =&gt; 'save_button' %&gt;
    &lt;%= submit_tag 'Continue', :name =&gt; 'submit' %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>&lt;% end %></p>
  
  <p>Selection.rb (model):</p>
  
  <pre><code>require 'active_model'
  
  class Selection
    include ActiveModel::Validations
    include ActiveModel::Conversion
    extend ActiveModel::Naming
  
    attr_accessor :answer
  
    validates_presence_of :answer
  
    def initialize(attributes = {})
      attributes.each do |name, value|
        send("#{name}=", value)
      end
    end
  
    def persisted?
      false
    end
  end
  </code></pre>
  
  <p>With only one form element other than the submit buttons, I received a nil error when I didn't select one of the radio buttons. I was able to get the validation to work properly when I did one of two things - add another field to the form and model or set a default value:</p>
  
  <pre><code>@selection = Selection.new(:answer =&gt; "N")
  </code></pre>
  
  <p>I elected to go with the default value solution, which did away with any need for validation, but was wondering if there was a better way of setting up my app if my users did not want a pre-selected answer.</p>