Misha Moroshko
Misha Moroshko

Reputation: 171429

Rails 3: How to control radio button selection via object's field?

In order to have a default value of select box, say:

<select name="job[worker_id]" id="job_worker_id">
  <option value="">Please select</option>
  <option value="1">Alex</option>
  <option value="2">Simon</option>
  <option value="3">Jessica</option>
</select>

I do the following in controller's "new" method:

@job.worker_id = 3 

How can I do something similar with radio buttons ?

The problem is that each button has its own id. For example:

<input type="radio" value="2" name="job[money_received]" id="job_money_received_2">
<input type="radio" value="1" name="job[money_received]" id="job_money_received_1">
<input type="radio" value="0" name="job[money_received]" id="job_money_received_0">

I would like to write in controller:

@job.money_received = 1

and have the "Part" button selected.

Any ideas ?

Upvotes: 1

Views: 8351

Answers (2)

fl00r
fl00r

Reputation: 83680

This

 @job.money_received = "1"

Should work great with form like this:

<%= f.radio_button :money_recieved, "1" %>
<%= f.radio_button :money_recieved, "2" %>
<%= f.radio_button :money_recieved, "3" %>

Radio with value = "1" will be checked

Upvotes: 5

m4risU
m4risU

Reputation: 1241

Try to use formtastic

https://github.com/justinfrench/formtastic

<%= semantic_form_for @job, :url => jobs_path do |f| %>
  <%= f.input :worker_id,  :as => :select,  :collection => @workers %>
  <%= f.input :money_received,  :as => :radio,  :collection => @money_received %>
<% end %>

There will be no logic to think about. Don't waste your time on forms.

mw

Upvotes: 1

Related Questions