1

I need a way for my form to not be sent if the user didn't bother to select any radio buttons.

I'd like to to that within the view and the controller, not in the model (the data shouldn't even be sent)

<%= form_tag("/bookings/new", method: "get") do %>
  <% @flights.each do |flight| %>
    <%= radio_button_tag :flight_id, flight.id %>
  <% end %>
  <%= submit_tag "book now" %>
<% end %>

edit, to clarify
normally I'd do
<%= f.text_field :name, required: true %>
but, as I have many radio buttons and I only need one for the form to work, I don't know how to implement it

Salomanuel
  • 805
  • 9
  • 20
  • What do you mean "the data shouldn't even be sent"? If you don't want the form to be submitted (i.e., no request/response cycle between the front end and the server), then you probably need to use javascript on the front end. – jvillian Oct 13 '17 at 13:48
  • You mean you want validation in front end and not in model? – krishnar Oct 13 '17 at 13:55
  • 1
    This question is more javascript-related than rails-related. Cf: https://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript – ArnoHolo Oct 13 '17 at 14:01

1 Answers1

1

You can set validation in the model to see the presence of checkbox if javascript is disabled. This is a more robust method.

validates :flight_id, :acceptance => true

Docs here - http://guides.rubyonrails.org/active_record_validations.html#acceptance

Edit

function validateCheckBox() {
    var x = document.getElementById("flight_id").checked;
    if(!x) {alert("Not checked")}        
}

<%= submit_tag "book now" , :onclick => "validateCheckBox();" %>
arjun
  • 1,546
  • 14
  • 31
  • As I wrote in the second line of my post, I'd like to to that within the view and the controller, not in the model – Salomanuel Oct 13 '17 at 14:07
  • 2
    When you talk about views and controller, that immediately translates to a front-end problem. Use javascript. See edit. – arjun Oct 13 '17 at 14:21