title: How to pass model attributes to coffeescript for select2 templating in Rails
body: <p>I'm trying to implement <a href="http://ivaynberg.github.com/select2/" rel="nofollow noreferrer">select2</a> in a Rails 3.2 app.</p>
  <p>Specifically, I want to use templating to display a country select field with country flags + country names.</p>
  <p>I have a Country model and User model. My Country model has a <code>:code</code> attribute. I'm using a CSS sprite to display flags, based on the <code>:code</code> attribute.</p>
  <pre><code>&lt;img class=&quot;flag flag-#{country.code}&quot;&gt;
  </code></pre>
  <p>In the User form I have</p>
  <pre><code>&lt;%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %&gt;
  </code></pre>
  <p>and in user.js.coffee.erb I have</p>
  <pre><code>jQuery -&gt;  
      format = (country) -&gt;
          &quot;&lt;img class='flag flag-#{country.code}' src='#'/&gt;&quot; + country.name       
      $('#prerep_country_id').select2
          placeholder: &quot;Select a country&quot;,
          allowClear: true,
          formatResult: format,
          formatSelection: format
  </code></pre>
  <p>I'm having trouble tying it all together (probably part of my ongoing learning of how asset pipeline and js.erb works).</p>
  <p>Currently the select field is rendered using select2, but contains only a list of countries. No formatting.</p>
  <p>How do I pass each country to the <code>format = (country)</code> function so that it gets formatted with the flag?</p>
  <p>Thanks for any pointers.</p>