Press "Enter" to skip to content

Cross Domain RESTful AJAX with jQuery and Rails 2.2.2

Flinn Mueller aka actsasflinn wrote an blog post Cross domain RESTful JSON-P with Rails back in July. There he showed how to monkeypatch Rails to allow json-p to do all the REST verbs even when going across domains. He also showed how to make the json-p calls with jquery. A very nice solution that we take advantage of in one of our apps. The only problem we had was that it stopped working when we upgraded to Rails 2.2.2.

There are other issues using this technique. To quote Flinn:

Achtung! Monkey patching with the above will expose your create method without using an actual post. Imho no big deal, others might be more cautious (CAPTCHAis always an option), ymmv.

See his original article for details on how to use it generally. 

The problem with the monkeypatch that he wrote up is that Rails 2.2.2 changed the function that was monkeypatched so the patch stopped working. Below is code that will work on both pre and post 2.2.2 Rails:

module ActionController
  class AbstractRequest

    def request_method

      if Rails::VERSION::STRING < "2.2.2"

        @request_method ||= begin

          method = (parameters[:_method].blank? ? @env['REQUEST_METHOD'] : parameters[:_method].to_s).downcase

          if ACCEPTED_HTTP_METHODS.include?(method)

            method.to_sym

          else

            raise UnknownHttpMethod, "#{method}, accepted HTTP methods are #{ACCEPTED_HTTP_METHODS.to_a.to_sentence}"

          end

        end

      else

        method = @env['REQUEST_METHOD']

        method = parameters[:_method] unless parameters[:_method].blank?

        HTTP_METHOD_LOOKUP[method] || raise(UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence}")
      end

    end

  end
end

One Comment

Comments are closed.