2

I'm trying to get the firstname(s) and lastname(s) which have the same id.
My Table Schema looks like this:

| id | nameable_id | nameable_type | value | type      |
| 1  | 2           | Person        | John  | Firstname |
| 2  | 2           | Person        | Doe   | Lastname  |

I want to use a collection_select with an expected output:

<select name="source[person_id]" id="source_person_id">
<option value="2">John Doe</option></select>`

How can I concatenate these values with the same nameable_id and order the firstname(s) then the lastname(s)?

wjordan
  • 19,770
  • 3
  • 85
  • 98
toxic2302
  • 23
  • 4

1 Answers1

1

Try this:

collection_select(:source, :person_id, Source.select("sources.id, GROUP_CONCAT(sources.value separator ' ') as name").group("sources.nameable_type,sources.nameable_id"), :id, :name, prompt: true)

Group_concat is for mysql only. If you use others database :

  • PostgreSQL: string_agg(sources.name, ' ')
  • Oracle: listagg(sources.name, ' ')
孙悟空
  • 1,215
  • 1
  • 11
  • 26
  • Thanks a lot. Your solution works for me with a little modification ;) ``f.collection_select(:person_id, Name.select("names.nameable_id, GROUP_CONCAT(names.value) as name").group("names.nameable_type, names.nameable_id"), :nameable_id, :name, prompt: true`` – toxic2302 Jan 10 '17 at 21:19