ruby-on-railsjs-routes

js-routes default url options set but still throwing 404


I am using js-routes as part of my ruby on rails project and I am trying to implement the default url options as per the github page. I have created the "jsroutes.rb" file in my configu/initializers folder, however, when I remove the :format => false from my rails routes.rb file that I added to get js-routes to work, I start to receive 404's again missing the format.

I have tried the following and confirmed they're being loaded via a puts statements on server start:

JsRoutes.setup do |config|
  default_url_options = {format: :json}
end

and

JsRoutes.setup do |config|
  default_url_options = {:format => 'json'}
end

and a few other variations that all result in the same.

My understanding is that, if I set this option, any request made via js-routes should automatically append the format as JSON. Is this wrong?

The errors spat out are the general rails 404's related to missing format such as this:

ActionController::RoutingError (No route matches [POST] "/purchases(.:format)")

An example usage of js-routes that will trigger this is below;

window.location.href=Routes.purchases_path

I have also been flushing the cache via "rake tmp:cache:clear" to ensure the js-routes file is regenerated every time I start the server.

What am I missing here?


Solution

  • So this was an interesting bug. It was caused by the fact that even though I was setting the URL option, and content type to 'application/json', I was passing the object to the AJAX call.

    As soon as I changed the data component of the AJAX call, to the object serialized as JSON, the calls succeed.

    I, incorrectly, assumed that passing the content type and an object to the AJAX call would automatically serialize the object to JSON.