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.

Category:
Notes
Tags:

Join the conversation! 1 Comment

  1. Thanks for posting. Solved my problem and it really was easy enough :)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.