Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails form_for collection_select ignoring remote ajax call that select_tag accepts

Before getting my form helper working, I was using the below for my select dropdown:

<%= select_tag :city_id, 
        options_for_select( City.all.collect{|c| [c.name,c.id]} ),
        :data => {  :remote => true,
                    :url => url_for(:controller => "locations", 
                                    :action => "filter_by_city")
                }
%>

and this worked perfectly to call my filter_by_city.js.erb and update some other values. Inspecting with firebug shows that it has the data-remote, etc, properties.

Changing to the form_for helper below, however, I get no data-remote, and thus no AJAX call.

<%= f.collection_select(:city_id, 
        City.all, :id, :name,
        :data => {  :remote => true,
                    :url => url_for(:controller => "locations", 
                                    :action => "filter_by_city")
                }
    )
%>

The dropdown appears exactly as before (and it took some muddling with the parameters to get that), but it has no functionality other than setting the params value.

I tried wrapping :data in {} (as from a french forum here but that wasn't the cure.

I assume it's a newbie mistake, but any help finding it will be most appreciated.

Thanks

like image 309
JayC Avatar asked Mar 13 '12 08:03

JayC


1 Answers

::le sigh::

When using collection_select, unlike some parts of RoR, it seems it's a bit picky to include all arguments in order. Even though I can (and continue) to leave out :post, the solution turned out to be including an empty set for options, and wrapping :data in {} for html_options.

And so, this is what works:

<%= f.collection_select(:city_id, 
        City.all, :id, :name, {},
        {:data => {  :remote => true,
                    :url => url_for(:controller => "locations", 
                                    :action => "filter_by_city")
                }
        }
    )
%>

Note the {} after :name and the { starting the next line.

Takeaway message - OPTIONS are NOT OPTIONAL if including html_options.

like image 52
JayC Avatar answered Sep 30 '22 13:09

JayC