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
编辑,澄清通常我会做<%= f.text_field:name,required:true%>但是,因为我有很多单选按钮,我只需要一个表单才能工作,我不知道如何实现它
1 个解决方案
#1
1
You can set validation in the model to see the presence of checkbox if javascript is disabled. This is a more robust method.
如果禁用了javascript,您可以在模型中设置验证以查看是否存在复选框。这是一种更健壮的方法。
validates :flight_id, :acceptance => true
验证:flight_id,:acceptance => true
Docs here - http://guides.rubyonrails.org/active_record_validations.html#acceptance
这里的文档 - 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();" %>
#1
1
You can set validation in the model to see the presence of checkbox if javascript is disabled. This is a more robust method.
如果禁用了javascript,您可以在模型中设置验证以查看是否存在复选框。这是一种更健壮的方法。
validates :flight_id, :acceptance => true
验证:flight_id,:acceptance => true
Docs here - http://guides.rubyonrails.org/active_record_validations.html#acceptance
这里的文档 - 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();" %>