0

我正在编辑 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 select helper - 默认选择值,如何?Rails form_for select tag with option selectedRails select helper - 默认选择值,如何?

4

2 回答 2

1

你可以在你的助手中尝试这样的事情

   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" } %>
于 2013-09-03T01:56:25.073 回答
0

您可以再传递一个参数来选择这样的值:

<%= f.select :start, options_for_select(@itinerary.locations), :selected => @newsavedmap.start,  {:include_blank => true}, {:id=>"startdrop" } %>
于 2013-09-03T09:04:11.487 回答