Have 2 tables - clients & case_managers
class Client < ActiveRecord::Base
has_one :case_manager
end
app/views/clients/_form.html contains line…
<% collection_select("client", "case_manager_id", \
case_manager.find_all, "name", "id") %>
and this line generates error…
undefined local variable or method `case_manager’ for
#<#Class:0xb7b93f84:0xb7b93b88>
What should the collection_select statement look like for it to populate
a pop-up select list of the names column from case_managers table?
for reference;
clients table has defined…
id integer primary key not null
case_manager_id not null
foreign key (case_manager_id) references case_managers(id)
case_managers table has defined
id integer primary key not null
name character varying 53 not null
no foreign keys
case_managers_clients table has defined
client_id integer not null
case_manager_id integer not null
no primary key
Craig W. wrote:
Maybe:
<% collection_select("client", "case_manager_id", \
CaseManager.find(:all), "id", "name") %>
supposing CaseManager is the model for your table
<% @case_managers = CaseManager.find(:all).collect {|c| [c.name, c.id]}
-%>
<%= select ‘client’, ‘case_manager_id’, @case_managers %>
Personally, I would put the first of the two statements in the
controller, because I don’t like seeing find() in the view.
If you have a large number of Case Managers, you could write a
more-optimized way of building that list, and make it a class method
in CaseManager.
class CaseManager < ActiveRecord::Base
def self.case_manager_options
managers = connection.select_all(“select name, id from
case_managers”)
managers.collect {|m| m.values}
end
end
Then, in your view, you can just do:
<%= select ‘client’, ‘case_manager_id’, CaseManager.case_manager_options
%>
Warning: People will now complain that this is premature optimization.
Only do it if it makes this easier/faster for you. Myself, I like
having this sort of thing taken care of by the model.
P.S. The difference between select and collection_select is that
select takes care of selecting the current value for you. Saves you a
step.
Good luck,
–Wilson.