Spätzle
Spätzle

Reputation: 747

getting the input from radio buttons on rails 4 view

I am working on a new view for the app we're using (Rails 4.1.6 on Ruby 2.0.0). The model has an integer attribute, max_operations. This is a limit we set and then use.

It can be either a natural number or -9, which we we to represent no limit. On the _form.html.erb, I want it to look something like this:

[...]

max operations

⃝ unlimited

⃝ limit: □ (tiny square to represent a text box)

[...]

If the unlimited option is selected, the value passed for the max_operations would be -9 and if the limit option is selected, the number typed in the adjacent text box would be passed.

I also want the field to be properly shown when editing the record (selecting the proper radio, value shown inside the text box if needed).

I'm not sure where to begin with. Trying to imitate some code examples were a complete failure. I did manage to produce this, which is probably the ugliest piece of code I've written in the last 15 years:

<input type="radio" id="operation_date_max_operations_unlimited" name="operation_date[max_operations]" <%= @operation_date.max_operations==-9?"checked=checked":"" %> value="-9"> <%=t("unlimited")%>
<br>
<input type="radio" id="operation_date_max_operations_limited" name="operation_date[max_operations]" <%= @operation_date.max_operations==-9?"":"checked=checked" %> value=<%= @operation_date.max_operations%> ><%=t("max_operations")%>:
<input type="text" id="max_operations_limit" name="operation_date[max_operations]" value=<%= @operation_date.max_operations==-9?"":@operation_date.max_operations %> >

it does show the things well but changing values does not work when saving, so I'd be glad to re-write the whole thing in a neat way.

I would like to keep it as much as I can within the erb code (<%=f.radio_button etc.), the less js the better. Any ideas?

Upvotes: 0

Views: 843

Answers (1)

sebkkom
sebkkom

Reputation: 1446

First of all, having a special number to represent something is generally not a good idea.

That said, in order to stick with this approach but also make it more "neat", you can have a method in your OperationDate model that tells you if there is a limit or not:

def limited_operations?
  (max_operations == -9)? true : false
end

Then, in your view, you can start bringing the radio buttons to your needs with the following:

<%= f.radio_button :max_operations, -9, { :checked => @operation_date.limited_operations? } %>
<%= f.radio_button :max_operations, @operation_date.max_operations, { :checked => @operation_date.limited_operations? } %>
<%= f.text_field :max_operations, :value => @operation_date.limited_operations? ? @operation_date.max_operations : "" %>

You can already see a danger here: The text field allows for any kind of values to be given..

Upvotes: 1

Related Questions