While creating a checkbox list for a nested form, I always forget syntax for it. So thought to write a post, so that I can use it as a reference in future and maybe it can help someone.
I have a User and Language model. User can have many languages and Language can have many users. I wanted a feature where I should be able to assign multiple languages to a specific user on a give screen. So I followed following method:
class User < ActiveRecord::Base
has_many :languages, :though => :user_languages
class Language < ActiveRecord::Base
has_many :users, :though => :user_languages
and I have one junction table language_users, which looks like following:
create_table "language_users", :force => true do |t|
So far it is all simple. Now I needed a form where I will display all available languages and languages opted by the selected user. Following is the view:
= form_for @user, :url => admin_user_path(@user) do |f|
- @languages.each do |language|
= check_box_tag "user[language_ids]", campaign.id, @user.languages.include?(language)
= submit_tag "Update"
pretty straight forward huh. I have a form_for a selected user. Looping through all available languages and marking checked if user has opted for a languages. If I want to assign/removed a language to this user, I will check/uncheck a checkbox and update.
Update method looks like following:
params[:user][:language_ids] ||= 
user = User.find params[:id]
and I am done here. It will do all the magic for me.