---
title: "三种Select helper"
author: "freesky1002"
date: "2007-11-23T11:26:52Z"
tags: []
slug: "select-helper"
draft: false
lastmod: "2007-11-23T11:26:52Z"
id: 142997
url: "https://freesky1002.iteye.com/blog/142997"
---

select:&lt;wbr&gt;&lt;/wbr&gt;  
    
select(object, method, choices, options = {}, html\_options = {})  
    
在ActionView::Helpers::FormOptionsHelper中定义

object是一個實體化變數，這裡很明顯的就是要擺上model物件嘛！  
method則是object的一個屬性，也是資料表中的對應欄位  
choices就是要被選的選項，可以是陣列或者是雜湊(Hash)  
options與html\_options則是一些選項在這邊來舉個例子吧

&lt;%= select("project", "teacher\_id", @teachers.collect{|t|   
  \[t.name, t.id]}, { :include\_blank =&gt; false }) %&gt;  
&lt;%=   
  select("project", "student\_id", {"CFC" =&gt; '1', "EF" =&gt; '2'})   
  %&gt;  
第一個例子中，@teachers在Controller是這樣的  
@teachers = Teacher.find(:all,   
  :select =&gt; 'id, name')

select\_tag:&lt;wbr&gt;&lt;/wbr&gt;  
  select\_tag(name, option\_tags =   
nil, options = {})  
    
在ActionView::Helpers::FormTagHelper中定義

如果你很喜歡手動打option的話..   
那用select\_tag準沒錯啦！  
在select\_tag中，name將會是params所接收值所用的鍵  
直接看範例

&lt;%= select\_tag 'user', "&lt;option&gt;CFC&lt;/option&gt;"   
  %&gt;  
這時在Controller中將會用params\[:user]來接收傳過來的值  
但是select\_tag也可以搭配options\_for\_select或者options\_from\_collection\_for\_select一起使用..   
  來看一個範例吧  
&lt;%= select\_tag('sid\[]',   
  options\_from\_collection\_for\_select(@students, 'id', 'name'), :multiple =&gt;   
  true)%&gt;  
因為加上了:multiple，所以可以接受多值選擇，這時在Controller接收到的sid將會是一個陣列，這也是我所卡住的地方..   
  (( 真丟臉

collection\_select:&lt;wbr&gt;&lt;/wbr&gt;  
    
collection\_select(object, method, collection, value\_method, text\_method, options   
\= {}, html\_options = {})  
    
在ActionView::Helpers::FormOptionsHelper中定義

如果資料來源是從資料庫來的話，可以使用這個來做下拉式選單。  
這個Object不用我說，就是你的model  
method呢？當然就是欄位啦  
其實嚴格說起來，這只是select+options\_from\_collection\_for\_select的組合啦！  
範例：

&lt;%= collection\_select(:payment, :id, @payments, :id, :name,   
  options ={:prompt =&gt; "-Select a continent"}, :class =&gt;"payment")   
%