开发者

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

I have band开发者_运维问答s, 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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜