Question

How would I add data- fields to the options in this options_for_select? This is for Rails 2.

I'd like to add something like

data-masterlocation-name="<%= location.masterlocation.inst_name %>" 

data-masterlocation-id="<%= location.masterlocation.id %>"

to each option. I tried following this approach (Rails Formtastic: adding "data-" field to option tag) but it doesn't seem to work for my situation. Thanks in advance for your help!

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

FINAL VERSION WORKS

Helper

module MaptryHelper

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

View

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

Solution

You can't do this with this method. You can however, write like this:

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

And in your helper:

def location_options(itinerary)
  itinerary.locations.map do |l|
    content_tag "option", l.name, location_option_attributes(l)
  end.join("\n")
end

private

def location_option_attributes(location)
  {
    :id => location.id,  
    :"data-masterlocation-name" => location.masterlocation.inst_name,
    :"data-masterlocation-id" => location.masterlocation.id
  }
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top