1

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?

neanderslob
  • 2,633
  • 6
  • 40
  • 82

1 Answers1

1

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} %>
bigsolom
  • 2,309
  • 1
  • 19
  • 15
  • Great solution. The lambda method threw a syntax error (it didn't like the colon between the two name types) that I got around using the following: `lambda {|company_or_person_object| company_or_person_object.instance_of? Company? rescue company_or_person_object.fname + " " + company_or_person_object.lname rescue company_or_person_object.name}` – neanderslob Oct 21 '15 at 23:17
  • 2
    is it possible to customize collection or group_method? for example instead :all I want to use .where(account_id: id) and instead :model_name I want to use model_name.gsub – Moh Feb 03 '16 at 23:57