To make my searching easier, I wanted to show just the name of the column in the option element but have it return the name of the parent table and the column name. For instance, I wanted the HTML to look like the following:
<select>
<option value="my_table.column_name">Column name</option>
</select>
The Rails API documentation shows many examples of using collection of objects from a model etc., but I couldn't find any examples using the column names from the model. So, after many failed attempts, I finally managed to get this syntax to work:
<%= options_for_select(MyTable.column_names.collect {|col| [col, "my_table." + col]} %>
In this example, I grab the column names using the built-in Rails method, then pass that array of strings to Ruby's collect method. The collect method accepts a block that allows me to create a new array where each element is itself an array. In these smaller arrays, I insert the column name directly and a string with the table name added to the beginning. The array created by the collect method is now of the proper format expected by the Rails options_for_select form helper.
I didn't think it would be this difficult, but in the end, I think the single line of code is pretty clean and simple.
Update
Well, I guess my idea wasn't that new and cool. As soon, as I posted this, I found the same solution in the API docs after all. I was just looking in the options_for_select section, not the select selection. See:
http://api.rubyonrails.com/classes/ActionView/Helpers/FormOptionsHelper.html#M001592
No comments:
Post a Comment