Rails 3 - 帮助评论模块

问题描述:

class CommentsController < ApplicationController 

    def create 

    @commentable= context_object() 
    @comment = @commentable.comments.build(params[:comment].merge(:user_id => current_user.id)) 

    if @comment.save 
     respond_to do |format| 
     format.js 
     end 
    else 
     render :action => 'new' 
    end 
    end 

    private 

    def context_object 
    params[:constraint][:context_type].singularize.classify.constantize.find(context_id) 
    end 

    def context_id 
    params["#{ params[:constraint][:context_type].singularize }_id"] 
    end 

end 

此评论模块为我提供了很好的服务,但今天早上我碰到了一个麻烦,可能是因为我使用了嵌套资源。从本质上讲,我现在有一个网址,如:Rails 3 - 帮助评论模块

/projects/3/albums/6/attachments/84 

当我在该网页上发表评论,我得到的错误:

ActiveRecord::RecordNotFound (Couldn't find Project without an ID): 
    app/controllers/comments_controller.rb:102:in `context_object' 
    app/controllers/comments_controller.rb:14:in `create' 

我的路线文件看起来像:

resources :projects do 
    resources : albums do 
    resources :attachments 
    end 
end 

resources :attachments do 
    resources :comments, :only => [:create, :update,:destroy], 
       :constraint => {:context_type => "conversations"} 
end 

任何想法关于如何让评论模块可以很好地与project>Album>Attachment发表评论?

感谢您的输入,

+1

我编辑了你的帖子以获得可读性。您能否澄清一下为什么您将资源评论嵌套在项目之外的附件>专辑层次结构中?你需要GET /附件并对它们发表评论吗?你有没有尝试过资源评论下面的附件项目>相册>附件? – tomeduarte 2011-01-26 00:14:12

发布本作中为了不弄乱评论原来的问题的答案。

既然你没有保持可用附件通过/attachments的要求 - 使第二资源块没用,做这样的事情:

resources :projects do 
    resources :albums do 
    resources :attachments do 
     resources :comments, :only => [:create, :update,:destroy], 
          :constraint => {:context_type => "conversations"} 
    end 
    end 
end 

这将改变你的路由助手(_path和_url) ,通过你的控制器和视图(s)并改变它们以反映你的新助手。

具体而言,attachment_comments_path变成project_album_attachment_comments_path

可以通过在控制台中运行rake routes来查看这些模型的完整路线列表。我也建议你仔细看看Rails routing guide