rails的actionviews提供了友好的form builder類來簡潔的動態生成表單元素,相比於簡單的textfield,select helper有一些特別,傳入參數較多,根據rails的api文檔,對select的使用說明如下:
引用
select(object, method, choices, options = {}, html_options = {})
object是指select選項所修飾的目標對象,method是目標對象的屬性(方法)名, choices是一個數組,包含了選擇項的‘name-value’值,options和html_options是選項。以person爲例,person有性別gender屬性,選項有[['男',0],['女',1]],用select來生成select元素的寫法爲:
Java代碼
- <%=select :person,:gender,[['男',0],['女',1]], {:include_blank=>true,:selected=>0}%>
<%=select :person,:gender,[['男',0],['女',1]], {:include_blank=>true,:selected=>0}%>
將生成
Java代碼
- <select name="person[gender]">
- <option value=""></option>
- <option value="0" selected="selected">男</option>
- <option value="1">女</option>
- </select>
<select name="person[gender]"><option value=""></option><option value="0" selected="selected">男</option><option value="1">女</option></select>
:include_blank=>true表示生成一項空選項。