Rails:如何设置具有 HABTM 关系的多个选择标签的表单

发布于 2024-10-06 22:52:58 字数 284 浏览 0 评论 0原文

我有 bandsgenresbands_genres 具有 HABTM 关系的数据库表

我有一个用于创建新乐队的表单,我希望用户能够从 3 个不同的下拉选择菜单中选择 3 种流派。

我将如何设置我的表单(以及我的 create 方法),以便当用户选择这 3 个流派时,它可以正确地将关系添加到我的 bands_genres 表中?

我正在运行 Rails 3.0.3。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柳絮泡泡 2024-10-13 22:52:58

您可以通过 1 个 select 来简化代码,它允许您选择多个选项,

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

:selected => 0 ,将默认选择设置为 None

gl

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

执手闯天涯 2024-10-13 22:52:58

您好,表单必须通过复选框与 HABTM 类似,

<%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%>

应该更改表单提交关系之后的内容

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文