2012-02-28 49 views
0

我處於一種奇怪的情況,在這種情況下,我得到一個嵌套資源的奇怪錯誤。具有嵌套資源和銷燬的RoutingError

我有一個嵌套的資源定義如下:

resources :users do 
    resources :comments, :only => [:create, :destroy] 
end 

我的終點徵求意見是JSON只有那麼它的控制器定義如下。請注意,我正在使用cancan和actsAsApi寶石。

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 

那麼我就可以發送POST請求與一些請求參數和註釋「/users/1/comments.json」將獲得創建像預期。不幸的是我得到它試圖找到一個錯誤的破壞作用:

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' 

作爲額外的信息,如果我修改的routes.rb這樣:

resources :comments, :only => [:destroy] 
resources :users do 
    resources :comments, :only => [:create] 
end 

我沒有看到任何錯誤。

回答

0

我已經能夠想出解決辦法的更多細節。基本上要求您在嵌套資源時使用respond_with,如下所示:

respond_with(@comment.note, @comment, :api_template => :default) 
0

因爲您使用的是嵌套資源,所以您需要告訴cancan加載用戶和評論以便操作評論。

見如下:

class CommentsController < ApplicationController 
    load_and_authorize_resource :user 
    load_and_authorize_resource :comment, :through => :user 
end 

見關於cancan nested resource page