Problem with radio buttons if input required (validates_presence_of)

Hi,

I am using two radio buttons ('yes', 'no') for one single field (here:
newsletter).
In my model I defined the field as required (validates_presence_of).
In my view, field value gets set based on user input. As default no
radio button is set initially.

The issue:
- If no selection is made by user, exception is thrown => good/expected
- If user selects 'Yes', field is set to true and everything works fine
- If user selects 'No', field is set to 'false', but
validates_presence_of still generates exception => no good/unexpected

Here are the code snipplets:
Model:
   validates_presence_of :newsletter,
                         :message => "Please select yes or no."
View:
  Yes<%= f.radio_button :newsletter, true %>
  No<%= f.radio_button :newsletter, false %>
  <%= error_message_on(:registration, :newsletter)%>

Any hint / advice is very much appreciated.
Thanks in advance!

Regards,
Knut

Okay, achieved to solve it by defining a custom validation.

   def validate
     if newsletter.nil?
       errors.add(:newsletter, "Please specify 'yes' or 'no'")
     end
   end

Knut Rollig wrote:

Hi,

I am using two radio buttons ('yes', 'no') for one single field (here:
newsletter).
In my model I defined the field as required (validates_presence_of).
In my view, field value gets set based on user input. As default no
radio button is set initially.

The issue:
- If no selection is made by user, exception is thrown => good/
expected
- If user selects 'Yes', field is set to true and everything works
fine
- If user selects 'No', field is set to 'false', but
validates_presence_of still generates exception => no good/unexpected

Here are the code snipplets:
Model:
  validates_presence_of :newsletter,
                        :message => "Please select yes or no."
View:
Yes<%= f.radio_button :newsletter, true %>
No<%= f.radio_button :newsletter, false %>
<%= error_message_on(:registration, :newsletter)%>

Any hint / advice is very much appreciated.
Thanks in advance!

Regards,
Knut

I think boolean's are handled differently, did you try
validates_inclusion_of?.

http://www.craigslistcloned.com
A craigslist clone in Rails