How do I convert this dropdown to a f.select in Ra

2020-05-03 09:35发布

I'm a Rails beginner and I'm working on a preexisting Rails 2 project. In my application, I tried converting a select dropdown field to a form_handler f.select, but I'm getting this error:

    undefined method `location.masterlocation.name

Here is my attempt:

    <% 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")%>

Here is the original dropdown field:

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

Thanks in advance for your help!

edit 1

I've gotten much closer using this code:

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

The problem is that I want to include the city, state, and zip in the value, all separated by commas. Any ideas about how to do this?

    <%= 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" %>     

THIS WORKS!

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 

View

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

1条回答
祖国的老花朵
2楼-- · 2020-05-03 10:31

Place the following in a helper file

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

Then in your view, you can use the following

= f.select :start, select_options_for_locations(@itinerary.locations),  {}, :id => "startdrop"
查看更多
登录 后发表回答