Rails中的select使用

假设有如下的下拉列表框

<select name="payment">
 <option value="1">VISA</option>
 <option value="2">MasterCard</option>
 <option value="3">Switch</option>
</select>


在rails中实现这类列表框,可以使用如下几个方法
1) 使用select
api:
select(object, method, choices, options = {}, html_options = {})

例如:
<%= select( "payment", "id", { "Visa" => "1", "Mastercard" => "2"}) %>

或者使用map填充
<%= select ("payment", "id", @payments.map {|u| [u.name,u.id]}) %>


对应的控制器中可以使用下列代码获取内容:
@payments = Payment.find(:all)
@selected_payment = @payments[2]



2) 使用select_tag
api:
select_tag(name, option_tags = nil, options = {})

用法如下:
<%= select_tag "payment", "<option>VISA</option>" %>

<%= select_tag "payment", options_for_select([ "VISA", "MasterCard", "Switch" ], "MasterCard") %>

<%= select_tag "payment", options_for_select(%w{ VISA Mastercard Switch }) %>
%w是字符串数组的简写方式,字符串数组中的每个字符串用空格隔开

下面可以实现多选
<%= select_tag 'payment[]', options_for_select(@payments), :multiple => true, :size => 3 %>
@payments是在控制器中定义的hash:
@payments = {'Visa' => 1, 'Mastercard' => 2, 'Switch' => 3}

对应的控制器中可以使用下列代码获取内容:
params[:payment]


3)使用 collection_select
api:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

用法如下:
<%= 
@payments=Payment.find :all
collection_select(:payment, :id, @payments, :id, :name, options ={:prompt => "-Select a payment"}, :class =>"payment") %>

对应的控制器中可以使用下列代码获取内容:
selected_payment = params[payment][id]

你可能感兴趣的:(html,Ruby,Rails)