Forum: Ruby on Rails Lookup from related tables

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Craig W. (Guest)
on 2006-01-30 02:19
(Received via mailing list)
I have been working on this for 3 days and haven't been able to solve

I have 2 tables...

belongs_to: case_managers

has_many: clients

When entering new clients, I need to have some type of select box that
allows me to pick the case_manager (by name) so that the 'id' field from
the case_manager table is inserted into clients.case_manager_id field.

I cannot figure out how to do that with either auto_complete or select
functions. This isn't exactly covered in Agile book.

Can anyone point me to an example of how this is done?


Bob S. (Guest)
on 2006-01-30 02:58
(Received via mailing list)
In your clients controller and the new action, load your casemanagers:


def new
  @client =
  @case_managers = CaseManager.find(:all)

<%= options = [['Select a Case Manager', '']] + @case_managers.collect {
|cm| [,] }
select 'client', 'case_manager_id', options %>

Something like that should work for you. Not tested though just off the
of my head.

Bob S.
Craig W. (Guest)
on 2006-01-30 08:00
(Received via mailing list)
Bob - thanks for taking the time to review my issue

I'm certain that I followed your instruction but I get an error that I
can't resolve...I've run into this error many times in all the various
methods that I've tried.

NoMethodError in Clients#new
Showing app/views/clients/_form.rhtml where line #21 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.collect

Extracted source (around line #21):

19: <p><label for="client_casemgr_name">Case Manager</label><br/>
20: <%# text_field_with_auto_complete(:case_manager, :name) %>
21: <%= options = [['Select a Case Manager', '']] +
@case_managers.collect { |cm| [,] }
22: select 'client', 'case_manager_id', options %>
24: <p><label for="client_casemgr_id">ID</label><br/>

Craig W. (Guest)
on 2006-01-30 08:24
(Received via mailing list)
Solved (finally) - thanks Bob

I had to use 'case_manager.collect' - not 'case_managers.collect'

Does this deserve a wiki page? This took days to work out.

Bob S. (Guest)
on 2006-01-30 09:10
(Received via mailing list)
Looking at your code, it appears your case_manager is actually casemgr
the db. Adjust your naming scheme appropriately. Remember, convention

Bob S.
Craig W. (Guest)
on 2006-01-30 09:43
(Received via mailing list)
No, the 'casemgr' thing you are seeing is only labels (not active code
areas) and I never bothered changing the labels - I have now.

I have solved that issue.

Thanks to your help

This topic is locked and can not be replied to.