0

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!

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327
Hacknightly
  • 5,109
  • 1
  • 26
  • 27

1 Answers1

1

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

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327
Austin Lin
  • 2,545
  • 17
  • 17
  • Wow sir, thank you very much. A gentleman and a scholar you are indeed. I searched for this answer for HOURS. Again, my thanks. – Hacknightly Dec 13 '10 at 21:36