views:

49

answers:

3

I'm calling a controller action to do a search with an AJAX request from 2 different pages and want to render a different rjs file based on which page requested the action. I could just make 2 actions to do this but it doesn't seem very DRY when it's the same code in the action just need different rjs as it's displaying the search results differently in the view.

Using Rails 2.3.4 and Ruby 1.8.7

+2  A: 

If I understand your question correctly, three ways come to mind to solve this:

  1. In your action, check the current request's http_referrer and try to figure out what page initiated the request. Depending on how you've got your routing set up, this may or may not work, but it does have the advantage of being pretty simple to do.
  2. Have your AJAX request include an extra GET parameter to identify which page the request is from. Then, have the Rails action test for that parameter, and render RJS accordingly.
  3. Do something clever with Routes and have page A hit the action from one distinct URL, and page B hit the action from another, and include the page identification parameter in the route configuration.

My preference would be for approach #2, as it seems way less likely to break randomly when your routing changes, and #3 strikes me as being overly complicated. There's probably a million other ways to do this, but those are the three that came to mind right off the bat. Hope that helps...

Steven Bedrick
#2 is usually the fastest and simplest.
Jonathan Julian
Thanks, #2 seems like a reasonable solution
Mark Robinson
+1  A: 

How much code is in the action? You could just factor that out into a common subroutine and call that from each action. It would keep the code simple and easy to understand, without resorting to clever tricks.

ScottJ
A: 

I usually do like #2 from Steven's answer, but with a twist. A filter in my ApplicationController attributes a custom mime type corresponding to the extra parameter.

That way, the names of my view files are clearer (i.e.: "show.employees-autocomplete.rjs", "show.quotation-autofill.rjs").

agregoire