Accessing a controller asynchronously usually requires writing a respond_to block in the corresponding action but I recently had the need to return a specific value in the same action based on the query string parameters.
Accessing an edit action via typical HTML view and an asynchronous may require something like this:
respond_to do |format| format.html format.js end
But I needed to return an asynchronous response based on a query string parameter. The relevant JavaScript source looks like this:
$('#contact_location').autocomplete({ source: '/contacts/new.js?type=location' }); $('#contact_position').autocomplete({ source: '/contacts/new.js?type=position' });
You can interrogate the params hash in the respond_to block like this:
respond_to do |format| format.html format.js { if params[:type] == "location" render :text => Contact.all.map(&:location).compact.reject(&:blank?) elsif params[:type] == "position" render :text => Contact.all.map(&:position).compact.reject(&:blank?) end } end
Easy enough.
Leave a Reply
You must be logged in to post a comment.