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
这个评论模块对我很有帮助但是我今天早上遇到了麻烦,可能是因为我使用了嵌套资源。基本上,我现在有一个URL:
/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
发表评论很好地合作的任何想法?
感谢您的输入,
答案 0 :(得分:0)
将此作为答案发布,以免将评论混淆为原始问题。
由于您没有要求通过/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),浏览您的控制器和视图并更改它们以反映您的新助手。
具体而言,attachment_comments_path
变为project_album_attachment_comments_path
。
可以通过在控制台中运行rake routes
来查看这些模型的完整路由列表。我还建议您仔细查看Rails routing guide。