I’m in a sort of weird situation where I’m getting a strange error with nested resources.
I have a nested resource defined as below:
resources :users do
resources :comments, :only => [:create, :destroy]
end
My end point for comments is json only so its controller is defined as follows. Take note that I am using cancan and actsAsApi gems.
class CommentsController < ApplicationController
load_and_authorize_resource
self.responder = ActsAsApi::Responder
respond_to :json
# POST /comments.json
def create
flash[:notice] = 'Comment was successfully created.' if @comment.save
respond_with(@comment, :api_template => :default)
end
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_with(@comment, :api_template => :default)
end
I can then send a post request to ‘/users/1/comments.json’ with some request parameters and the comment will get created like expected. Unfortunately I am getting an error where it tries to locate the destroy action:
Completed 404 Not Found in 169ms
ActionController::RoutingError (No route matches {:action=>"destroy", :controller=>"comments", :id=>#<Comment id: 34, user_id: 1, text: "test test test", created_at: "2012-02-28 06:45:49", updated_at: "2012-02-28 06:45:49">}):
app/controllers/comments_controller.rb:12:in `create'
As extra information, if I modify routes.rb to this:
resources :comments, :only => [:destroy]
resources :users do
resources :comments, :only => [:create]
end
I don’t see any error.
I have been able to figure this out. Basically it is required that when you nest resources you use respond_with as follows: