I’ve been trying to sort out a multiple select dropdown but haven’t
found any good examples - anyone know of any or perhaps could make a
suggestion [see below]
Michael K. wrote:
| Nice, are there any functions like this for handling one to many
| relations? i.e a User has_and_belongs_to_many :groups.
collection_select requires a source object and an instance method. With
has_many, this method can be the foreign key. But with
has_and_belongs_to_many there is no corresponding instance method since
the keys are in a separate join table, so you’ll want to manage the
parameters yourself. Here’s an example using
options_from_collection_for_select to create a multiple select:
class User < ActiveRecord::Base
~ # id, name fields
~ has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
~ # id, name fields
~ has_and_belongs_to_many :users
end
class UserController < AbstractApplicationController
~ model :user
~ def edit
~ case @request.method
~ when :get
~ @user = User.find(@params[‘id’])
~ @available_groups = Groups.find_all - @user.groups
~ when :post
~ @user = User.find(@params[‘user’][‘id’])
~ @user.groups << Group.find(@params[‘add_groups’])
~ redirect_to :action => ‘show’, :id => @user.id
~ end
~ end
end