簡體   English   中英

如何在此Rails 2選擇表單中設置所選選項?

[英]How do I set a selected option in this Rails 2 selection form?

我正在編輯Rails 2應用程序。 在其中,用戶提交了一個包含下拉菜單的表單,該信息在我的數據庫中創建了一條記錄。 當用戶去編輯記錄時,我想在下拉菜單中顯示已保存的“選定”選項。 但是,我不斷收到錯誤消息。 這是我的設置:

查看選擇字段

    <% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
    <%= f.select :start, options_for_select(@itinerary.locations), {:include_blank => true}, {:id=>"startdrop" } %>      

表格助手

    def options_for_select(locations)
  locations.map do |l|
    content_tag "option", l.masterlocation.name, location_option_attributes(l)
  end.join("\n")
end

private

def location_option_attributes(location)
  {
    :value => "#{location.masterlocation.street_address}, #{location.masterlocation.city}, #{location.masterlocation.state}, #{location.masterlocation.zip}",
    :id => location.masterlocation.id,  
    :"data-masterlocation-name" => location.masterlocation.name,
    :"data-masterlocation-id" => location.masterlocation.id,
    :"data-masterlocation-latitude" => location.masterlocation.latitude,
    :"data-masterlocation-longitude" => location.masterlocation.longitude
  }
end

我試圖使視圖看起來像這樣:

    <%= f.select :start, options_for_select(@itinerary.locations, @newsavedmap.start), {:include_blank => true}, {:id=>"startdrop" } %> 

但是我對該行的參數數目錯誤(2為1))。 也嘗試過

    <%= f.select :start, options_for_select(@itinerary.locations), {:selected => @newsavedmap.start, :include_blank => true}, {:id=>"startdrop" } %> 

但是當我去編輯保存的地圖時,沒有任何預選。 我嘗試了以下這些鏈接,並不斷予以淘汰。 感謝您提供的任何幫助!

Rails選擇助手-默認選擇值,如何? Rails form_for選擇標記且選擇選項的選擇Rails選擇助手-默認選擇值,如何?

您可以在助手中嘗試類似的方法

   def options_for_select(locations, selected=nil)
      locations.map do |l|
        tag_options = location_option_attributes(l)
        if l == selected
         tag_options[:selected] = "selected" 
        end
        content_tag "option", l.masterlocation.name, tag_options
      end.join("\n")
    end

然后像您之前嘗試的那樣致電字段。

<%= f.select :start, options_for_select(@itinerary.locations, @newsavedmap.start), {:include_blank => true}, {:id=>"startdrop" } %>

您可以再傳遞一個參數來選擇值,如下所示:

<%= f.select :start, options_for_select(@itinerary.locations), :selected => @newsavedmap.start,  {:include_blank => true}, {:id=>"startdrop" } %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM