2013-08-30 39 views
0

我是一个Rails初学者,我正在开发一个预先存在的Rails 2项目。在我的应用程序,我尝试了选择下拉字段转换为form_handler f.select,但我得到这个错误:如何将此下拉菜单转换为Rails中的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> 

在此先感谢您的帮助!

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

的问题是,我想包括在价值的城市,州和邮编,所有分离:

编辑1

我已经使用这个代码变得更接近由逗号。有关如何做到这一点的任何想法?

<%= 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助手:

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

放置在一个辅助文件视图中的下列

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" 
+0

我得到这个错误'ActionView :: TemplateError(未定义的方法名称为#)'。作为背景,newsavedmap belongs_to:行程,以及行程has_many:地点。表单本身位于matry.html.erb视图中。 maptry has_many:newsavedmaps。不知道它是否重要,但我在Rails 2 – KDP

+0

虽然我使用了不同的解决方案,但它是基于jvnill的输入。谢谢您的帮助! – KDP