2

我正在尝试获取具有相同 ID 的名字和姓氏。
我的表架构如下所示:

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

我想使用collection_select具有预期输出的 a:

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

我怎样才能将这些值与相同的值连接起来,nameable_id然后排序名字然后是姓氏?

4

1 回答 1

1

尝试这个:

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 仅适用于 mysql。如果您使用其他数据库:

  • PostgreSQL: string_agg(sources.name, ' ')
  • 甲骨文:listagg(sources.name, ' ')
于 2017-01-10T15:27:02.387 回答