I'm using grouped_collection_select
with polymorphic associations to assign either a company
or person
to a task. The issue is that people have a first name and a last name, while a company just has a name. I would like to use a concatenation of :fname
and lname
as the option_key_method
for the person group in the menu and I would like to use :name
as the option_key_method
for the company group in the menu.
I however haven't run across this in my Google investigation. As it stands, I'm using :email
as the option_key_method
because it's the most distinguishing field that's shared by the two models:
<%= f.grouped_collection_select :entity_id, [Company, Person], :all, :model_name, :to_global_id, :email %>
How might I set it up to make use of the two different kinds of name fields that are implemented by the two different models?
You can pass a lambda method to the option_key_method
, which takes the object currently in hand Person
or Group
in your case and you can do the processing you want on it
Example:
<%= f.grouped_collection_select :entity_id, [Company, Person], :all, :model_name, :to_global_id, lambda {|company_or_person_object| company_or_person_object.instance_of? Company ? company_or_person_object.fname + company_or_person_object.lname : company_or_person_object.name} %>