2

I have a table named items and three boolean columns fixed_amount, no_price, per_hour.

How can I add radio buttons of the above three columns to a form in order to submit as true if one is selected and false to rest of the columns that are not selected? I want the radio button to be able to toggle from one to another and not to select all three of them.

Currently I'm trying something like the following but without any luck:

<%= form.radio_button :no_price, '1', checked: true %>
<%= form.radio_button :fixed_amount, '1' %>
<%= form.radio_button :per_hour, '1' %>
3
  • 2
    I'd go with enum instead of separate columns, this was it's way easier and logically more correct: e.g enum pricing_option: { no_price: 0, fixed_amount: 1, per_hour: 2 } then in views: <%= collection_radio_buttons(:foo, :pricing_option, Foo.pricing_options, :first, :first)%> Commented Oct 5, 2018 at 10:13
  • check control radio button list apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/… Commented Oct 5, 2018 at 10:37
  • Thanks @Said Kaldybaev. this just worked fine! Commented Oct 5, 2018 at 10:45

2 Answers 2

1

I'd go with enum instead of separate columns, this was it's way easier and logically more correct: e.g

enum pricing_option: { no_price: 0, fixed_amount: 1, per_hour: 2 }

In views:

<%= collection_radio_buttons(:foo, :pricing_option, Foo.pricing_options, :first, :first)%>

Sign up to request clarification or add additional context in comments.

Comments

1

To have the radio buttons untoggle each other, they need to have the same name. Something like

<%= radio_button_tag :price_option, 'no_price', checked: model.no_price? %>
<%= radio_button_tag :price_option, 'fixed_amount', checked: model.fixed_amount? %>
...

Then you will receive in params[:price_option] the selected option, and set up your model accordingly.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.