繁体   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