Hi. I’m still getting adjusted to Rails coding, and and stumbled into a
piece of code that in my mind, shouldn’t work, but it does. I know Rails
is smart, but…take a look.
I’m trying to populate a select box with first and last names, which are
stored in separate fields: employee.lname and employee.fname.
@employees = Employee.find(:all, :order => “name”)
I wanted the box to display “lname, fname” and tried to use the
collection_select method to easily assign :id to each option value. I
assumed using collection_select wouldn’t work because it only lets me
specify one field for option text. So I tried making a new hash with a
@users = Array.new
@employees.each do |employee|
@users.push([employee.id => employee.lname << ", " << employee.fname])
And in my template, I have:
<%= collection_select(:profile, :user, @employees, :id, :lname) %>
And lo and behold, I get a text box with each name formatted like
“Smith, John.” But I don’t see how its possible, since in my
collection_select statement, I reference the original @employees hash
and not @users. I also only specify :lname as a parameter. But if I take
out the each loop, it goes back to only listing the last name. What
gives? The only explanation I can think of is if the @employees.each
loop is modifying @employees hash itself.