Stpn
Stpn

Reputation: 6394

Rails radio buttons - one choice for multiple columns in on model

I want user to choose one option out of three for one model.

I.e. I have a model Video, that can be rated as positive/negative/unknown

Currently I have three columns with boolean values (pos/neg/unknown).

Is it the best way to handle this situation?

What should the form look like for this?

Currently I have something like

<%= radio_button_tag :positive, @word.positive, false %> 
<%= label_tag :positive, 'Positive' %>
<%= radio_button_tag :negative, @word.negative, false %> 
<%= label_tag :negative, 'Positive' %>
<%= radio_button_tag :unknown, @word.unknown, false %> 
<%= label_tag :unknown, 'Positive' %>

But obviously it allows multiple selections, while I am trying to restrict it to just one..

What to do?

Upvotes: 5

Views: 5210

Answers (2)

Damien
Damien

Reputation: 27473

If would go with a string column let's say rating.

then in your form:

# ...
<%= f.radio_button :rating, 'unknown', checked: true %>
<%= f.radio_button :rating, 'positive' %>
<%= f.radio_button :rating, 'negative' %>
# ...

It only allows one selection

edit The exact same but using radio_button_tag:

<%= radio_button_tag 'rating', 'unknown', true %>
<%= radio_button_tag 'rating', 'positive' %>
<%= radio_button_tag 'rating', 'negative' %>

Upvotes: 9

KL-7
KL-7

Reputation: 47618

I think you need smth like this:

<%= radio_button_tag :rating, 'positive', @word.rating == :positive %> 
<%= label_tag :positive, 'Positive' %>
<%= radio_button_tag :rating, 'negative', @word.rating == :negative %> 
<%= label_tag :negative, 'Positive' %>
<%= radio_button_tag :rating, 'unknown', @word.rating == :unknown %> 
<%= label_tag :unknown, 'Positive' %>

Here all radio buttons will have the same name attribute (that is 'rating') but will have different value attribute ('positive', 'negative' and 'unknown' respectively). In the last parameter you pass true or false to mark one of them as selected.

Upvotes: 1

Related Questions