How to pass model attributes to coffeescript for select2 templating in Rails
-
12-06-2021 - |
Question
I'm trying to implement select2 in a Rails 3.2 app.
Specifically, I want to use templating to display a country select field with country flags + country names.
I have a Country model and User model. My Country model has a :code
attribute. I'm using a CSS sprite to display flags, based on the :code
attribute.
<img class="flag flag-#{country.code}">
In the User form I have
<%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
and in user.js.coffee.erb I have
jQuery ->
format = (country) ->
"<img class='flag flag-#{country.code}' src='#'/>" + country.name
$('#prerep_country_id').select2
placeholder: "Select a country",
allowClear: true,
formatResult: format,
formatSelection: format
I'm having trouble tying it all together (probably part of my ongoing learning of how asset pipeline and js.erb works).
Currently the select field is rendered using select2, but contains only a list of countries. No formatting.
How do I pass each country to the format = (country)
function so that it gets formatted with the flag?
Thanks for any pointers.
La solution
From the fine manual:
formatSelection
Function used to render the current selection.
formatSelection(object)
and the object
parameter is
The selected result object returned from the
query
function.
And a little further down we see what query
is all about, in particular:
Array of result objects. The default renderers expect objects with
id
andtext
keys. Theid
attribute is required, even if custom renderers are used.
And if we look at an example (http://jsfiddle.net/ambiguous/a73gc/), we'll see that your format
function is being passed a country
object with id
and text
keys. You, on the other hand, are looking at country.code
but there's nothing there and you produce images like this:
<img class='flag flag-' src='#'/>
so you don't get any flags.
Try this instead:
format = (country) ->
"<img class='flag flag-#{country.id}' src='#'/>" + country.name
#--------------------------------^^
Presumably you have height
and width
in your img.flag
CSS already so we don't have to worry about how big the flags are.
Also, if you're using HTML5, you can lose the XML-style />
self-closing tag thing, just <img ...>
is fine.