Find_by_column_name and for loop returns undef method `each'

I’m trying to understand how to select only certain rows in my database
using RoR.

As a test I try to find certain clients by adding this code in my list
view…

<% clientlist = Client.find_by_client_status_id(1) %>
<% if clientlist %> <= This prevents me from getting nil errors.
<% for client in clientlist %> <= This seems to try and call ‘each’
method.

and data display …
<% end %>
<% end %>

My clients table has a client_status_id column that I’m trying to use.
It has values for each client such as 1, 2, 3 that corresponde with a
client_status table.

If I do Client.find(:all) in the first line I get all rows from the
database so everythng else seems to be working toherwise.

Once I figure out the correct find_by syntax I think I should move it
into a client model method also.

Any ideas?

Guest wrote:

I’m trying to understand how to select only certain rows in my database
using RoR.

Couple things here.

First, use your controller to do your queries.

def show_clients
@clientlist = Client.find_all_by_client_status_id(1)
end

Notice find_all is the variant you want here, not find_by, to get a list
of all clients matching your status ID of 1. If there are none, you get
an empty array, not nil.

Now in your .rhtml you can do this:

<% for client in clientlist %>

... <% end %>

Make sense?

Jeff

Thanks Jeff - Adding the show_clients method into my
clients_controller.rb didn’t work right off, even if I put it within the
def list method. Placing it in application_help.rb or clients_helper.rb
is working though.

I also removed the "@clientlist = " and just call “for clients in
show_clients” to get the list.

Thanks for the pointer. I seems to be working now.

If it’s more proper to place the query into the controller rather than a
helper is there something different I need to do to get it working
there? My application_helper.rb is getting swollen with lot’s of little
find(:all) queries and I’d like to do as right as possible.

find_by returns only one record… and .each is a method of array Same
as
find :first, :condition…

find_all_by_client_status should work for you :slight_smile:

Good luck