views:

14

answers:

1

I'm trying to setup an ajax-based website that loads a fragment of a webpage when a specific combination of GET variables and HTTP Headers are given.

GET /normal/html/page?ajax=true
X-ajax: true

What I've setup in my controller is:

before_filter do |controller|
  if request_by_ajax?
    ApplicationController.layout false
  end
end

This works, but only in development mode. You see when I attempt to access the given page it only gives the fragmented (layout free) page.

When the normal page is accessed without ajax:

GET /normal/html/page

This returns only the view for that page and NOT the layout around it. But if I access that page when the webserver is reloaded then it returns the layout and when its accessed afterwards via AJAX it returns the layout + the view. Clearly there is a caching issue here.

I would really like to keep the same route for the page. If there is an ajax call then I would prefer to figure out the response based on the querystring and request header values. But rails prefers to classify querystring parameters and request headers as meaningless when serving a file (i.e. /normal/html/page and /normal/html/page?ajax=true) return the same actual template file (this what I assume).

Any idea how to get around this?

+1  A: 

I figured out the issue.

It turns out that the layout call must be defined early on in the application controller:

---- application_controller.rb
layout :choose_layout

def choose_layout
  if request_by_ajax?
    false
  else
    'application'
  end
end

Works like a charm.

matsko