Reputation: 5392
I'm currently reading Learning Rails 3. I'm working on an example where you can create students and awards. A student has_many awards and award belongs_to student.
in the app/views/awards/_form.html.erb part of the code looks like this:
<div class="field">
<%= f.label :student_id %><br />
<%= f.select :student_id, Student.find(:all).collect {|s| [s.name, s.id]} %>
</div>
the book explains this code like this:
"That’s where the collect method is useful. It takes a block as an argument ({}). The |s| is a very brief way of saying that Ruby should loop through the collection of students and put each row into a variable named s. On each iteration of the loop, the block will return an array, contained in [ and ]. Each of those arrays, which will become lines in the select list, will have two values. The first is the name of the student.. That value will be displayed to the user. The second is the id value for the student, and that value will be what comes back from the form to the server."
My question is about the last sentence. Why and how is the second value returned from the form to the server? Why not the first value as well? And what's the purpose of sending an array [s.name, s.id] into the collect method and why the need for this collect method at all?
thanks, mike
Upvotes: 0
Views: 75
Reputation: 712
Sentence could be misunderstood, but it is simple:
Student.find(:all).collect {|s| [s.name, s.id]} simple create an array of array:
[["Mike", 1],["John", 3], ["Mary", 8]]
This array allows you to create the select HTML tag:
<option value="1">Mike</option>
<option value="3">John</option>
<option value="8">Mary</option>
Upvotes: 1