Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to setup a form with multiple select tags with a HABTM relationship

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

I have a form for creating new bands and I want users to be able to select 3 genres from 3 different dropdown select menus.

How would I set up my form (and my create method) so that when the user selects those 3 genres, it correctly adds the relationship to my bands_genres table?

I'm running Rails 3.0.3.

like image 357
Shpigford Avatar asked Dec 29 '22 04:12

Shpigford


2 Answers

You can simplify your code by doing it via 1 select which allows you to select multiple choices,

<%= 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 selection to None

gl

like image 133
sameer Avatar answered Apr 28 '23 19:04

sameer


Hi the form must be similar to the HABTM through checkboxes Something like

<%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 form submit relationships should be changed

like image 28
Bohdan Avatar answered Apr 28 '23 18:04

Bohdan