Michael Durrant
Michael Durrant

Reputation: 96454

No route matches [POST] for ajax json request

Mu current routes for groups are:

resources :groups do
  resources :links # Enables group/:id/link/new
  collection do
    post 'order_links'
  end 
  # I tried adding: 
  # collection do
  #   post 'show'
  # end
end 

How do I add a 'POST" route for show so that a json show request can be used?

I tried just get 'show', i.e.

  resources :groups do
    resources :links # Enables group/:id/link/new
    collection do
      post 'order_links'
    end
    get 'show'
  end

but I get

Error loading: <!DOCTYPE html>
...
<h1>Routing Error</h1>
<p><pre>No route matches [POST] &quot;/groups/42&quot;</pre></p>
<p>

Upvotes: 0

Views: 1029

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

Resourceful

Michael, perhaps you'd be better suited to using the standard CRUD actions as defined in the Rails resourceful routing structure:

enter image description here

As demonstrated, you have a GET show action by convention, meaning you can use this route with the corresponding respond_to block, to define the response for JSON:

#app/controllers/groups_controller.rb
Class GroupsController < ApplicationController
   def show
      @group = Group.find params[:id]
      respond_to do |format|
        format.html
        format.json { render json: @group.to_json }
      end
   end
end
  • I don't know what you want to perform with this - so I've just posted the @group variable to your JSON request

--

Mime Types

I think you're getting confused with the role of mime types with Rails

Your controller#actions are not restricted to your mime types directly. The mime types are just a way to determine the type of request being sent, not which action is going to process it

Therefore, you may be better suited to sending the request to a controller you already have in your system (by virtue of the resources directive), and then determine the response based on the mime type (in your case JSON).

You can do this by handling the request as so:

#app/assets/javascripts/application.js
$.ajax({
   url: "groups/" + $(this).attr("href"),
   success: function(data) {
      alert(data);
   }
});

Upvotes: 1

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

I want to make an ajax call and examples seem to want a post route (see error). Is it ok to use get if I am only requesting data ?

if you are just fetching the data from database , you are free to use get, actually this is what get request is typically designed for.

Upvotes: 0

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

you can do this

resources :groups do
    resources :links # Enables group/:id/link/new
    collection do
      post 'order_links'
      post 'show'
    end
 end

Upvotes: 0

Related Questions