On 18 Aug 2006, at 11:46 pm, Shauna wrote:
> I''ve added a drop-down list of first and last names of borrowers
to a
> form. How do I sort them by LastName, FirstName in the drop-down?
I''d do it something like this. In the controller, make a special
collection called @borrowers_for_select:
@borrowers = Borrower.find(:all, :order => "last_name, first_name")
@borrowers_for_select = @borrowers.map{|b| [b.first_name + '' ''
+
b.last_name, b.id]}
Then in the view use:
<%= select(:loan, :borrower_id, @borrowers_for_select,
{:include_blank => true}) %>
There''s a lot going on here, so let''s work backwards.
First, the ''select'' helper in the view. This constructs the
entire
<select><option></option>...</select> lump for you. The
parameters are:
1. The name of the object that this input refers to (in this case,
it''s @loan).
2. The name of the attribute in that object that this input refers to
(in this case, it''s @loan.borrower_id).
3. A list of choices, formatted as an array of arrays:
[ [name1, value1],
[name2, value2],
[name3, value3], ...]
where each ''name'' is what appears in the drop-down list in the
browser, and each ''value'' is what actually gets submitted when
you
submit the form. So in your case, we want to put first_name+last_name
into the names, and the borrower IDs into the values.
Also note that the order of this array determines the order that the
choices will appear in the drop-down list.
4. Misc. options, which in this case is the option :include_blank,
which inserts a blank choice at the top of the list.
Now let''s look at the code in the controller. This line:
Borrower.find(:all, :order => "last_name, first_name")
finds all of your borrowers, and then orders them by their last name
and then their first name. It''s generally neater to have your
database do the sorting for you wherever possible, rather than
sorting the array yourself.
Then, this line:
@borrowers.map{|b| [b.first_name + '' '' + b.last_name, b.id]}
uses the ''map'' method of Array to transform the array of
Borrower
objects into the format that we want for the ''select'' helper
in the
view. The ''map'' method iterates through each member of
@borrowers,
takes the result of the block (which in our case assembles a mini-
array for each borrower that looks like [name, id]), and slots it
into a new array. In other words, ''map'' is a way of applying a
given
bit of code to each member of an array.
Then, we have a @borrowers_for_select which is in the right format
for the ''select'' helper in the view.
Does that all make sense? Let us know if you have any questions.
Chris
P.S. I''ve just realised that I used the style
''first_name'' for your
column names instead of what you''ve got, which is
''FirstName''. Change
as necessary (although if you want to be really Railsish you could
change your column names to the standard_rails_convention!).