如何将此下拉列表转换为Rails中的f.select?

时间:2013-08-30 01:25:26

标签: ruby-on-rails forms rails-activerecord

我是Rails初学者,我正在研究预先存在的Rails 2项目。在我的应用程序中,我尝试将选择下拉字段转换为form_handler f.select,但我收到此错误:

    undefined method `location.masterlocation.name

这是我的尝试:

    <% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>

    <%= f.select(:start, options_from_collection_for_select(@itinerary.locations, "location.masterlocation.street_address, location.masterlocation.city, location.masterlocation.state, location.masterlocation.zip", "location.masterlocation.name"), :id => "startdrop")%>

以下是原始下拉字段:

    <select id="startdrop">
    <option value="">
    <% for location in @itinerary.locations %>
    <option value="<%= location.masterlocation.street_address %> <%= location.masterlocation.city %>, <%= location.masterlocation.state %>, <%= location.masterlocation.zip %>"><%= location.masterlocation.name %></option>
    <% end %>
    </select>

提前感谢您的帮助!

编辑1

我使用这段代码的时间越来越近了:

    <%= f.select :start, options_for_select(@itinerary.locations.map{ |c| [c.masterlocation.name, c.masterlocation.street_address]}),{}, :id=>"startdrop", :name=>"startthere" %>     

问题是我想在值中包含city,state和zip,所有这些都用逗号分隔。关于如何做到这一点的任何想法?

    <%= f.select :start, options_for_select(@itinerary.locations.map{ |c| [c.masterlocation.inst_name, c.masterlocation.street_address AND , AND c.masterlocation.city AND , AND c.masterlocation.state AND, AND c.masterlocation.zip]}),{}, :id=>"startdrop", :name=>"startthere" %>     

这个工作!

Maptry Helper:

    module MaptryHelper

def options_for_select(locations)
  locations.map do |location|
    [location.masterlocation.name, location_string(location.masterlocation)]
  end
end

def location_string(masterlocation)
  "#{masterlocation.street_address}, #{masterlocation.city}, #{masterlocation.state}, #{masterlocation.zip}"
end

    end 

查看

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

1 个答案:

答案 0 :(得分:1)

将以下内容放在帮助文件中

def select_options_for_locations(locations)
  locations.map do |location|
    [location_string(location.masterlocation), location.masterlocation.street_address]
  end
end

def location_string(masterlocation)
  "#{masterlocation.city}, #{masterlocation.state}, #{masterlocation.zip} #{masterlocation.name}"
end

然后在您看来,您可以使用以下

= f.select :start, select_options_for_locations(@itinerary.locations),  {}, :id => "startdrop"