Reputation: 5325
I have a collection_select that fires some JS to set an id in my URL when the click occurs. Here is the code.
application.js
$(document).ready(function(){
$("#org_id").on("change", function(){
val = $(this).val();
window.location = '/sessions?org_id='+ val;
});
});
view
<div id="org-select">
<%= collection_select :org, :id, Org.all, :id, :name %>
</div>
rendered html
<div id="org-select">
<select id="org_id" name="org[id]"><option value="1">bustas</option>
<option value="2">wintas</option></select>
What all of this does is give me a url like /sessions?org_id=2.
The issue I am having is that the select box in the page defaults to the first org, and when the user changes the option in the select, the page fires/refreshes, but the page defaults back to that first org, so the id in the URL does not change.
Upvotes: 1
Views: 1066
Reputation: 35
Try to use options_for_select. And give params[value] in selected area. Your code will be like:
Rails:
<%= select_tag "org_id", options_for_select(Org.all.collect{ |o| [o.name, o.id] }, {:selected => "#{params[:org_id] if params[:org_id].present?}"}), {} %>
Upvotes: 1
Reputation: 15089
Well, collection_select
does have an option to set the default value. As you can see on the last example provided by some user here:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
What you can do is set the selected value to the params you are getting from the url, something like this:
<%= collection_select :org, :id, Org.all, :id, :name, {:selected => params[:org_id]} %>
The ?org_id=2
part of the url is translated to params[:org_id]
internally, so you can use it like the example above.
Give it a try and see if it works.
Upvotes: 0