Shweta Shetty
Shweta Shetty

Reputation: 23

Rails 3 collection_select helper method for a HABTM relationship

I have 2 models, sessions and presenters with a HABTM relationship between them. On the create session page, I would like to provide a drop down box from which the user may select multiple presenters for the session. My code in the _form.html.erb (for sessions) is

<%= f.label :presenters %>
<%= collection_select(:session, :presenters, Presenter.all, :id, :name,{:include_blank => ''},{:multiple => true})%>

However on hitting create I get the following error message on my browser: Presenter(#2176431740) expected, got String(#2151988680)

The request log shows "presenters"=>["1","2"]

I am guessing that an array of strings containing the ids of the selected presenters is being returned instead of presenter objects. I cannot understand how to get this to work.

(PS- I have created the presenters_sessions table and specified has_and_belongs_to_many in both models)

Thanks in advance.

Upvotes: 2

Views: 1563

Answers (1)

Adam Carr
Adam Carr

Reputation: 2986

I you haven't figured this out, it will work if you pass in :presenter_ids as the second parameter rather than :presenters. In the end, you are just mapping the selected ids to the model's id collection. The error is saying "You tried to assign a string to a collection of Presenters".

Upvotes: 3

Related Questions