Forum: Ruby on Rails HABTM and collection select problem

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
6c4fb2e03ccc9e26d6c837989807fba9?d=identicon&s=25 Michael Slater (Guest)
on 2007-06-14 09:59
(Received via mailing list)
I've been beating my head on this seemingly simple problem all evening
and would appreciate any pointers.

I have an Admin model and an Assistant model, both subclasses of User,
and with a HABTM relationship to each other (admins have many
assistants, and one assistant may work for multiple admins).

I have a join table called admin_assistant with columns of admin_id
and assistant_id.

In the form to create an Admin, I have:

<%= f.collection_select('assistant_id',
@assistants_list, :id, :name ) %>

While displays fine, but when the controller create action tries to
create the new Admin, I get:

Assistant expected, got String

The params have the ids for the selected assistants as an array of

"admin"=>{"name"=>"Joe Smith", "assistants"=>["2", "3"], ...}

I've googled all over for this and it seems most people get this
because the column name doesn't have _id, which I already have. But
none of the examples I could find used HABTM relationships -- does
this technique not work with the join table? What am I missing here?

Thanks for any pointers you can provide.

6c4fb2e03ccc9e26d6c837989807fba9?d=identicon&s=25 Michael Slater (Guest)
on 2007-06-16 00:36
(Received via mailing list)
I found a way to get collection_select to work with a HABTM
relationship, by using the following for collection select:

<%= collection_select('user', 'assistant_ids',
@assistants_list, :id, :name, {}, {:multiple => true, :name
=>'user[assistant_ids][]' } ) %>

But it seems more complicated than it should be, and not well
documented. Am I missing a simpler way to do this? Or is really a rare
thing to be using collection_select with an HABTM relationship?

(In my case, it is a self-referential habtm relationship, but that
doesn't seem to be the issue. I abandoned the subclasses mentioned in
the description below for other reasons.)


P.S. Thanks to srjoseph who submitted this doc patch that gives this
This topic is locked and can not be replied to.