7stud -- wrote in post #1016089:
Leoncio Caminha wrote in post #1016087:
the field name:
collection_select(:post, :author_id, Author.all, :id,
:name_with_initial, :prompt => true)
will generate:
<select name="post[author_id]">
<option value="">Please select</option>
<option value="1" selected="selected">D. Heinemeier Hansson</>
<option value="2">D. Thomas</option>
<option value="3">M. Clark</option>
</select>
Okay, so it looks like the first two arguments determine the name of the
select?
And even that isn't entirely correct. Apparently, the name of the
select has to be of the form:
an_existing_model[:an_existing_field_name_in_that_model]
which doesn't make any sense to me.
I'm not sure why that is -- you're inside of a form builder, building a form for an object that you plan to modify when you submit that form, right? What you're describing here is precisely how Rails builds forms, and what it expects to receive when you send your controller the params hash.
Now let's say you want to add a select field to your Post to choose a Topic. Post has_one :topic.
<%= form_for @post do |f| %>
<%= f.collection_select :topic_id, Topic.all, :id, :name, :prompt => true %>
That gives you:
<select name="post[topic_id]" id="post_topic_id" size="1">
<option value="">Please choose...</option>
<option value="42">Life, the Universe, and Everything</option>
...
If you wanted to pick a favorite color from an array, you could do that like this:
<%= f.collection_select :favorite_color %W(red green blue), :to_s, :titleize, :prompt => true %>
That gives you:
<select name="post[favorite_color]" id="post_favorite_color" size="1">
<option value="">Please choose...</option>
<option value="red">Red</option>
...
In either case, when you create or update a Post, you send the hash params[:post] to its ccontroller, and all the parameters nested inside of that hash are untwisted in there and assigned to the object.
It's really very flexible.
Walter