Lookup from related tables

I have been working on this for 3 days and haven’t been able to solve
it.

I have 2 tables…

clients
belongs_to: case_managers

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?

Thanks

Craig

In your clients controller and the new action, load your casemanagers:

client_controller.rb:

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

views/clients/_form.rhtml:
<%= options = [[‘Select a Case Manager’, ‘’]] + @case_managers.collect {
|cm| [cm.name, cm.id] }
select ‘client’, ‘case_manager_id’, options %>

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

Bob S.
http://www.railtie.net/

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):

18:
19:

Case Manager

20: <%# text_field_with_auto_complete(:case_manager, :name) %>
21: <%= options = [[‘Select a Case Manager’, ‘’]] +
@case_managers.collect { |cm| [cm.name, cm.id] }
22: select ‘client’, ‘case_manager_id’, options %>
23:
24:

ID

Craig

Looking at your code, it appears your case_manager is actually casemgr
in
the db. Adjust your naming scheme appropriately. Remember, convention
over
configuration.

Bob S.
http://www.railtie.net/

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

Craig

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.

Craig

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs