开发者

Rails HABTM Question

开发者 https://www.devze.com 2023-01-30 23:06 出处:网络
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. A business has and belongs to m

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. 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? 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. I have a multiple select box setup in on of my applications code is below. In your example, simply replace annoucement with business.

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

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'}

0

精彩评论

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

关注公众号