I was building a utility in rails that would allow users to input merchandise data.  Data would be sorted by the type of merchandise (clothes vs. electronics, etc.)  I created the main model for the merchandise selection, and put a placeholder dropdown there. Once I had the data populating, I wanted to create this dynamic dropdown value option.

In other words, I want users to create the types of merchandise they will input.  Then in the form when they go to type in their data, they would have a dropdown for “type” and it would have the types appropriate… this way I wouldn’t have to hard code those values (as they would most likely change, customer by customer.)

Dynamic Population

Initially it seemed pretty straight forward, I created another model for the type (it had one field name of type string) and a controller to set up the CRUD actions.

Sure enough it was populating the database for the “type” table.  What I needed now, was a way to mix the data from the type table as values passed into the form.


Rails has a dynamic form generation utility called form_for and a function of that utility is the collection_select method.

This method allows me to do something like this:

<%= f.collection_select :item_type, ItemType.order(:name), :id, :name, {:prompt => true} %>

In the above code, I’m using :id and :name… These values correspond as the value_method (example above of :id) and text_method (example above of :name) As mentioned in this StackOverflow.com article, the text_method is what is displayed… in this case the string stored in the :name symbol I made. However, the value_method (what is stored in the database for this item type) will be the ID of that type… If you want to store the string (and not the numeric ID), you would change the value_method to be that of your string (in my example :name.)

The cool factor here, is that the table I’m saving into is the Merchandise table. It has a field called item_type that takes a string. Great. So now I am using the form_for to populate the values in that dropdown with data from the ItemType table.

User Flow

Users first would be presented with an administration task to set up the item types they expect for their merchandise.  One customer might be selling electronics, so it might have types such as: radio, phones television, parts

Another customer might be into clothing, with types like: dresses, tuxedos, children’s clothing, suits, ties

Each customer would create/edit/delete whatever types they want, whenever they want.  Later as a data entry person steps in, they are using a different interface which gives them a form to fill out for each new item.  This interface has that dropdown render with the appropriate types.



No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments