Rails: how to customize a form with multiple select tags with a HABTM relationship

I have database bands , genres and bands_genres tables with a HABTM relationship

I have a form for creating new groups, and I want users to be able to choose 3 genres from 3 different drop-down menus.

How can I customize my form (and my create method) so that when the user selects these 3 genres, he correctly adds the relation to my bands_genres table?

I am running Rails 3.0.3.

+4
source share
2 answers

Hi, the form should look like a HABTM via checkboxes. Sort of

 <%form_for @band do |f|%> ... <%= select_tag "band[genree_ids][]", options_from_collection_for_select(@first_genrees, "name", "id")%> <%= select_tag "band[genree_ids][]", options_from_collection_for_select(@second_genrees, "name", "id")%> <%= select_tag "band[genree_ids][]", options_from_collection_for_select(@third_genrees, "name", "id")%> <%end%> 

after the form submission relationship needs to be changed

+2
source

You can simplify your code by executing it with 1 select, which allows you to select multiple options,

 <%= collection_select(:band, :genre_ids, Genre.all, :id, :name,{:include_blank => 'None'}, {:multiple => true, :name=>'band[genre_ids][]',:selected => 0}) %> 

The: selected => 0, sets the default parameter to None

GL

+8
source

All Articles