我正在编辑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 - Default selected value, how?,Rails form_for select tag with option selected,Rails select helper - Default selected value, how?
答案 0 :(得分: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" } %>
答案 1 :(得分:0)
您可以再传递一个参数来选择这样的值:
<%= f.select :start, options_for_select(@itinerary.locations), :selected => @newsavedmap.start, {:include_blank => true}, {:id=>"startdrop" } %>