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

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

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

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

Is this the best way to handle this situation?

What does the form look like for this?

I currently 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 choice, while I try to limit it to only one.

What to do?

+4
source share
2 answers

If you came across a row column, say rating .

then in your form:

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

It allows only one choice.

edit The same, but with radio_button_tag:

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

I think you need something 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 the radio buttons will have the same name attribute (i.e. 'rating' ), but will have a different value attribute ( 'positive', 'negative' and 'unknown' respectively). In the last parameter, you pass true or false to mark one of them as selected.

+1
source

Source: https://habr.com/ru/post/1384977/


All Articles