Reputation: 33755
I have two models User
and Category
that have a HABTM association.
I would like to generate checkboxes from a collection of Category
items on my view, and have them associated with the current_user
.
How do I do that?
Thanks.
P.S. I know that I can do the equivalent for a dropdown menu with options_from_collection_for_select
. I also know that Rails has a checkbox_tag
helper. But not quite sure how to do both of them. I know I can just do it manually with an each loop or something, but am wondering if there is something native to Rails 3 that I am missing.
Upvotes: 0
Views: 125
Reputation: 50057
Did you check out formtastic or simple_form
They have helpers to write your forms more easily, also to handle simple associations.
E.g. in simple_form
you can just write
= simple_form_for @user do
= f.association :categories, :as => :check_boxes
In form_tastic
you would write
= simple_form_for @user do
= f.input :categories, :as => :check_boxes
Hope this helps.
Upvotes: 2
Reputation: 19249
You can use a collection_select and feed it the options. Assuming you have a form builder wrapped around a user instance, you can do something like this:
form_for current_user do |f|
f.collection_select(
:category_ids, # the param key, so params[:user][:category_ids]
f.object.categories, # the collection of items in the list
:id, # option value
:name # option string
)
end
You may want to pass the :multiple => true
option on the end if needed.
Upvotes: 0