title: How do I add data fields to the options for options_for_select in Rails?
body: <p>How would I add data- fields to the options in this options_for_select? This is for Rails 2. </p>
  
  <p>I'd like to add something like</p>
  
  <pre><code>data-masterlocation-name="&lt;%= location.masterlocation.inst_name %&gt;" 
  
  data-masterlocation-id="&lt;%= location.masterlocation.id %&gt;"
  </code></pre>
  
  <p>to each option. I tried following this approach (<a href="https://stackoverflow.com/questions/7624824/rails-formtastic-adding-data-field-to-option-tag/9076805#9076805">Rails Formtastic: adding &quot;data-&quot; field to option tag</a>) but it doesn't seem to work for my situation. Thanks in advance for your help!</p>
  
  <p>Maptry Helper:</p>
  
  <pre><code>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 
  </code></pre>
  
  <p>View</p>
  
  <pre><code>&lt;%= f.select :start, options_for_select(@itinerary.locations),{}, :id=&gt;"startdrop", :name=&gt;"startthere" %&gt;     
  </code></pre>
  
  <p><strong>FINAL VERSION WORKS</strong></p>
  
  <p>Helper</p>
  
  <pre><code>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 =&gt; "#{location.masterlocation.street_address}, #{location.masterlocation.city}, #{location.masterlocation.state}, #{location.masterlocation.zip}",
      :id =&gt; location.masterlocation.id,  
      :"data-masterlocation-name" =&gt; location.masterlocation.name,
      :"data-masterlocation-id" =&gt; location.masterlocation.id
      }
    end
  end
  </code></pre>
  
  <p>View</p>
  
  <pre><code>&lt;%= f.select :start, options_for_select(@itinerary.locations), {}, {:id=&gt;"startdrop", :name=&gt;"startthere"} %&gt;      
  </code></pre>