Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to use radio button correctly in rails?

Writer Sophia Terry

I'm trying to create some radio buttons and I'm not sure how to. Following this question I've got it set up working almost correct, but I'm new to this and not sure why I can't figure it out completely. So what I'm doing is putting a label to group the boolean and then have radio buttons which are labeled Yes and No. If the user clicks the label of Yes it should select the radio button yes (right now they can only click the button itself). This is my code as follows:

 <div> <%= f.label :autolyse %><br /> <%= f.label :autolyse, "Yes", :value => "Yes" %> <%= f.radio_button :autolyse, true%> <%= f.label :autolyse, "No", :value => "No" %> <%= f.radio_button :autolyse, false, :checked => true %> </div>

The first label is for the group, it labels the group "Autolyse". Then I want a Label for "Yes", which if selected will will set true, and then obviously the next one is for False. How do I get this set up correctly?

3 Answers

see label(object_name, method, content_or_options = nil, options = nil, &block)

 <div> <%= f.label :autolyse %><br /> <%= f.label :autolyse, "Yes", value: "true" %> <%= f.radio_button :autolyse, true %> <%= f.label :autolyse, "No", value: "false" %> <%= f.radio_button :autolyse, false, checked: true %> </div>
2

If you want to keep selected the option chosen by the user, you should validate the param, would be something like this:

<div> <%= f.label :autolyse %><br /> <%= f.label :autolyse, "Yes", :value => "true" %> <%= f.radio_button :autolyse, true, !!params[:autolyse] %> <%= f.label :autolyse, "No", :value => "false" %> <%= f.radio_button :autolyse, false, !!params[:autolyse] %>
</div>

If you want to do it from the object properties you just replace the params variable for the object property:

<div> <%= f.label :autolyse %><br /> <%= f.label :autolyse, "Yes", :value => "true" %> <%= f.radio_button :autolyse, true, [email protected] %> <%= f.label :autolyse, "No", :value => "false" %> <%= f.radio_button :autolyse, false, [email protected] %>
</div>
1

Rails will automatically have correct radio button checked based on the attribute value:

 .p = f.label :published, t(".published") = f.label :published, t(".yes"), value: true = f.radio_button :published, true = f.label :published, t(".no"), value: false = f.radio_button :published, false

published yes no

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.