2011-01-25 82 views
1
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

回答

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) ,通過你的控制器和視圖(s)並改變它們以反映你的新助手。

具體而言,attachment_comments_path變成project_album_attachment_comments_path

可以通過在控制檯中運行rake routes來查看這些模型的完整路線列表。我也建議你仔細看看Rails routing guide