Link to home
Start Free TrialLog in
Avatar of depassion
depassionFlag for Philippines

asked on

radio buttons to display list of options - rails app

so i have this collection select to select a category of job:

<%= collection_select(:job, :category_id, Category.all, :id, :name, {:include_blank => '-select job type-'} ) %>

Open in new window


instead i want to show the categories as a list of radio buttons a user can select rather than a drop down list.
Avatar of kristinalim
kristinalim
Flag of Philippines image

Did you happen to mean check boxes?

If you take a look at the has_many method in the Rails API, a has_many association sets up Job#category_ids and Job#category_ids= for the job instance:
@job.category_ids # => [1, 2, 3]
@job.category_ids = [1] # => [1]

Open in new window

So in your view you could do:
<% Category.all.each do |category| %>
<li>
  <%= check_box_tag 'job[category_ids][]', category.id, f.object.category_ids.include?(category.id) %>
  <%= category.name %>
</li>
<% end %>

Open in new window

With check boxes, though, if no check box has been checked no data for that form name would be sent to the server. In your controller action, you would have to ensure the value passed for categories_id is an array:
# If no check box in the set has been checked
params[:job][:category_ids] # => nil

# Set to a blank array to catch these cases.
params[:job][:category_ids] ||= []
@job.update_attributes(params[:job])

Open in new window

Avatar of depassion

ASKER

i did actually mean radio button as in the category section here https://jobs.37signals.com/jobs/new, as only 1 category can be selected
ASKER CERTIFIED SOLUTION
Avatar of kristinalim
kristinalim
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks