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)?
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, ' ')