kdweber89
kdweber89

Reputation: 2174

Sorting outcomes from ruby for loop

I am trying to pull some information from my local active record database. (these are doctors).
Initially in my view I had an each loop like so

<% @doctors.each do |doctor| %>

This was nice, and it pulled the list of all of the doctors that I need. However now I need to have these guys pulled, but also in alphabetical order, based on their name.

So my approach with this was so,

<% for last_name in @doctors.last_name.all(:order => "last_name") %>

and then i end up calling it later in the code like so

<%= doctor.last_name %>

However I keep getting an error. The error I get is..

undefined method `last_name' for #

In my rails console, I am able to find a doctors last name by going,

doctor.last.last_name

So, i'm not sure why the method is undefined when I am able to still easily find it in the database. Would anybody have any idea what i am missing with this?

Upvotes: 1

Views: 61

Answers (1)

joem
joem

Reputation: 331

The @doctors collection will not have a last_name attribute, you need to do something like :

@doctors = Doctor.all.order(:last_name)

then

<% @doctors.each do |doctor| %>
    <%= doctor.last_name %>
<% end %>

Upvotes: 1

Related Questions