三种Select helper

select:<wbr></wbr>
  
select(object, method, choices, options = {}, html_options = {})
  
在ActionView::Helpers::FormOptionsHelper中定义



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

<%= select("project", "teacher_id", @teachers.collect{|t| 
  [t.name, t.id]}, { :include_blank => false }) %>
<%= 
  select("project", "student_id", {"CFC" => '1', "EF" => '2'}) 
  %>
第一個例子中,@teachers在Controller是這樣的
@teachers = Teacher.find(:all, 
  :select => 'id, name')

select_tag:<wbr></wbr>
  select_tag(name, option_tags = 
nil, options = {})
  
在ActionView::Helpers::FormTagHelper中定義

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

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

collection_select:<wbr></wbr>
  
collection_select(object, method, collection, value_method, text_method, options 
= {}, html_options = {})
  
在ActionView::Helpers::FormOptionsHelper中定義

如果資料來源是從資料庫來的話,可以使用這個來做下拉式選單。
這個Object不用我說,就是你的model
method呢?當然就是欄位啦
其實嚴格說起來,這只是select+options_from_collection_for_select的組合啦!
範例:

<%= collection_select(:payment, :id, @payments, :id, :name, 
  options ={:prompt => "-Select a continent"}, :class =>"payment") 
%

你可能感兴趣的:(html)