Matilda
Matilda

Reputation: 1718

Rails JSON url encoding does not parse .json/.xml

I have the following rails route

resources :apps do
  post "name/:text/,
     :on => :member, :action => :register, :as => :register,
     :text => /[^\/]+/

end

The url that hits it in json format is the following:

curl -v -s -H "Content-type: application/json" -d '' -X POST http://0.0.0.0:3000/apps/1/name/hello.json

When my rails controller receives the request above, it can't see that the .json at the end of the url is part of the url encoding/extension and not part of hello. It sees the params as the following:

Parameters: {"id"=>"1", "text"=>"hello.json"}

instead of having "text" => "hello".

I also have respond_to :json in my AppsController.

Any idea why this happens? and how to make rails parse the .json out?

Upvotes: 0

Views: 175

Answers (2)

Matilda
Matilda

Reputation: 1718

Doing :format => true in the route fixed this issue for me. Looks like adding (.:format) worked for @H-man.

Also this is the reference for :format http://guides.rubyonrails.org/v3.2.13/routing.html#route-globbing

However setting :format => true forces the format to be always presented, and :format => false pretty much ignores the format, which is what's happening now.

I realized the issue was with my regex /[^\/]+/ matches everything besides / which matches .json as well.

Upvotes: 0

Hesham
Hesham

Reputation: 2347

Two things:

  • You didn't include the format part in your route, i.e: /path/to(.:format)
  • I'm not really sure what your regex does, but you may want to review it

I tried the following and it seems to work fine:

resources :apps do
  post "name/:text(.:format)",
     :on => :member, :action => :register, :as => :register,
     :text => /[a-z]+/

end

Upvotes: 1

Related Questions