Rails 4 Form Dropdown Menu with collection_select

Perhaps this was simple for you, but as someone still learning rails, I found confusing and conflicting examples and explanations on how to use collection_select in a rails form, especially with a has_many through association using accepts_nested_attributes_for.  It took me several hours to finally get it working.  Hopefully this will save you some time.

So I have a PurchaseOrder model that is linked to the Items model via a has_many through association, with the join model called Quantities, as you can see below.


Screen Shot 2013-12-18 at 5.15.51 AM


Screen Shot 2013-12-18 at 5.17.28 AM


Screen Shot 2013-12-18 at 5.18.30 AM

And I have a form with nested fields using accepts_nested_attributes_for that looks like this:


Screen Shot 2013-12-18 at 5.21.34 AM

which looks like this in the browser:

Screen Shot 2013-12-18 at 5.23.45 AM

and here’s the _quantity_fields.html.erb partial:

Screen Shot 2013-12-18 at 5.26.10 AM

So here is how I got the dropdown menu for “Part Number” using collection_select.

What I had trouble with was what variables to pass into the collection_select function.  They go as follows:

collection_select ‘model field’, ‘collection of options in the dropdown menu’, ‘model field for values’, ‘model field to show in the menu’

You’ll notice the @items that I passed in to the collection_select.  I created this in the PurchaseOrders controller in the new, create, edit, and update functions:

@items = Item.all.order("part_number")

I read the official rails documentation for collection_select, but it still left me a bit confused.   I also found help from two StackOverflow questions (one, two) that I want to give credit to, and may help you as well.

Let me know if this helped you!


4 Responses to Rails 4 Form Dropdown Menu with collection_select

  1. Pingback: What I learned today | Rails 4 Form Dropdown Menu with collection_select

  2. seanosaur says:

    Thanks for the assistance with the dropdown!

    In regards to formatting the code in your post, go to the text editor (not visual) and add


    tags around it all. You might have to copy/paste it into the text side side it likes to break up the into “<” Hope this helps!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: