2017-01-10 30 views
2

我試圖獲得具有相同編號的名字和姓氏。
我的表結構是這樣的:collection_select concat名字和姓氏相同的編號

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

我想使用與預期輸出collection_select

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

我如何可以連接這些值具有相同nameable_id和秩序的名字(S )那麼姓氏?

回答

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,'')
+0

非常感謝。 ) ''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