2011-09-08 46 views
47

Đối với mã được đưa ra bên dưới, tôi muốn giữ hộp chọn được chọn với giá trị được chuyển.đường ray select_tag giá trị đã chọn

Nhưng điều này không làm việc:

@yrs =[2011,2010,2009,2008] 
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,:selected=>2011) %> 

Xin cho biết tôi làm thế nào để đi về nó.

Cảm ơn

+0

Nếu câu trả lời cung cấp bởi @M Tariq Aziz, hoạt động, xin vui lòng chấp nhận nó. –

Trả lời

82

Xóa phần :selected=>.

Cú pháp:

options_for_select(@options, @selected_options) 

Cách sử dụng:

options_for_select(1..5, 3) # creates a range 1..5 , with 3 as selected by default 
5

Chỉ cần làm rõ @M Tariq Aziz câu trả lời:

Mã của bạn sẽ trông như thế này:

@yrs =[2011,2010,2009,2008] 
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,2011) %> 

Định dạng chung cho chọn thẻ là:

<%= select_tag 'year', options_for_select(:collection, :selected) %> 
+1

Tôi đã có số nguyên làm giá trị khóa như đang sử dụng chuỗi làm giá trị đã chọn. Nơi bạn sử dụng to_a tôi cần phải sử dụng to_i. Cám ơn đã chỉ tôi hướng đi đúng. Điều này làm việc cho tôi: <% = select_tag (: map_set_priority_filter, options_for_select (MapSet.priority_filters.collect {| priority | [priority.name, priority.id]}, @ map_set_priority_filter.to_i))%> – John

25
<%= select_tag "page_type", options_for_select(@page_type.collect{ |u| [u.data_name, u.id]}, :selected=>@page.page_type), {:class =>"select_combobox",:onchange=>"reset_form(this.id,'page_type_msg');"} %> 

làm việc này cho tôi :)

Các vấn đề liên quan