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. 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'}
精彩评论