简体   繁体   English

Rails HABTM问题

[英]Rails HABTM Question

and first of all thank you for reading my question. 首先,感谢您阅读我的问题。

I'm fairly new to Rails, and have a has_and_belongs_to_many relationship set up in my application. 我是Rails的has_and_belongs_to_many ,并在我的应用程序中设置了has_and_belongs_to_many关系。 A business has and belongs to many categories , and a category has and belongs to many businesses . 一个企业具有并属于许多类别 ,而一个类别具有并属于许多企业

How might I go about creating a drop down selection menu for the categories inside of the businesses/new.html.rb form? 如何为businesss / new.html.rb表单内的类别创建下拉选择菜单? I can't seem to figure out how I associate the two when creating a new business. 我似乎无法弄清楚在创建新业务时如何将两者联系在一起。 I'm sure it's something simple. 我敢肯定这很简单。 Please help! 请帮忙! Thank you! 谢谢!

Use the collection_select tag. 使用collection_select标记。 I have a multiple select box setup in on of my applications code is below. 我在下面的应用程序代码中有一个多重选择框设置。 In your example, simply replace annoucement with business . 在您的示例中,只需用business代替annoucement

<%= collection_select 'announcement', 'category_ids',
        Category.all, :id, :name, 
        { :include_blank => 'None'}, 
        { :multiple => true, 
          :name =>'announcement[category_ids][]',
          :selected => 0 } %>

edit: You can remove :multiple => true if you don't want to have a multiple select. 编辑:如果您不想进行多重选择,则可以删除:multiple => true

The :selected => 0 sets the selected element on load to the first item in the list, which I am setting as 'None' using {:include_blank => 'None'} :selected => 0将加载时的选定元素设置为列表中的第一项,我使用{:include_blank => 'None'}将其设置为'None'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM