2

I have a simple rails project that I've been playing around in with reactjs. To add some basic navigation, I brought the js-routes library in and it works great for urls that have a path parameter such as "localhost:3000/addresses/1".

The problem I am facing is I am trying to call a "new" resource method and it adds the (::format) literally to the url which of course bombs as localhost:3000/addresses/new(.:format) is an invalid path.

I reference the "new_address_path" path as specified in the routes-js docs. The rake output for this url is below:

new_address_path    GET /addresses/new(.:format)    addresses#new

The HTML snippet utilizing the above path looks like this:

<a href={Routes.new_address_path}>Create am address</a>

ENV:

-Ruby: 2.2.4
-Rails: 4.2.6
-js-routes: 1.2.8

Route in question:

resources :addresses

What am I missing here? It seems like it is not interpreting the rails route file properly.

webster
  • 3,902
  • 6
  • 37
  • 59
gwnp
  • 1,127
  • 1
  • 10
  • 35

3 Answers3

0

I am not sure if I got your question. If you want to generate url with format suffix you can use format option in the helper method. For example:

Routes.new_address_path(format: 'js')

will generate something like this:

/addresses/new.js
Maciej Małecki
  • 2,725
  • 19
  • 29
  • Sorry. I meant, my route is using the default rails route type of "resource" which automatically appends a (::format) to the end of the URLs so that it can accept different formats. When working in ERB files, I do not have to specify a format, rails figures out whether it's html/json etc. I would expect the same behaviour from js-routes, am I mistaken? I could pass the format but it seems like a waste. Does this help? – gwnp Aug 10 '16 at 16:00
0

Sorry I thought I posted my solution in here.

The problem wasn't js-routes but rather my AJAX call, I was setting the content type to JSON and I assumed that it was converting my object to JSON using the built in methods. This is not true, you need to manually convert the object to JSON via JSON.stringify(obj).

Old ajax call:

....
url: Routes.feedback_path(),
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: obj,
....

New ajax call:

....
url: Routes.feedback_path(),
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(obj),
....
gwnp
  • 1,127
  • 1
  • 10
  • 35
0

You might have found a solution, but your original problem is one with js-routes, or rather your use of it.

You have to provide the parens to get the correct output from js-routes.

Original: Routes.new_address_path

Fixed: Routes.new_address_path()

As smefju posted, you can specify the format in the parens, but completely leaving them off is not an option.

Troy S
  • 89
  • 1
  • 3