Slippery John
Slippery John

Reputation: 757

How do I add an attribute to a rails select dropdown?

Okay, so I'm trying my hand at some ajax in rails and have hit a massive brick wall: I can't set the data-remote attribute in my select box. No matter what form I try it in, it always acts as if the parts telling it about that attribute aren't even there. Example:

<%= f.select(:image, options_from_collection_for_select(@images, 'id', 'name'), data: {remote: true}) %>
<%= f.select( [...] , :'data-remote' => 'true') %>
<%= f.select( [...] , :data => {remote: true}) %>
<%= f.select( [...] , data: {remote: true}) %>
<%= f.select( [...] , remote: true) %>

I even have working code that implements the first three on other things, but just not that f.select

So does anybody know how I can properly apply an attribute to an f.select?

Upvotes: 0

Views: 255

Answers (2)

nicosantangelo
nicosantangelo

Reputation: 13716

Try this:

<%= f.select :image, options_for_select(@images.map{ |i| [i.name, i.id, {'data-remote'=>true}] }) %>

Upvotes: 0

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

The data key needs to be in an HTML options hash which is the third argument to select. From the documentation:

select(method, choices, options = {}, html_options = {})

Therefor you need:

f.select(:image, options_from_collection_for_select(@images, 'id', 'name'), {}, { data: {remote: true} })

Note the empty options hash.

Upvotes: 2

Related Questions