2011-05-11 64 views
0

錯誤:沒有路由錯誤傳遞參數時通過的link_to

No route matches {:action=>"new", :controller=>"comments", :parent_id=>1}

的routes.rb:

MyApp::Application.routes.draw do 
    resources :posts do 
    resources :comments 
    end 
    resources :topics do 
    resources :posts 
    end 
    root :to => "posts#index" 
end 

型號:

class Topic < ActiveRecord::Base 
    has_many  :posts, :dependent => :destroy 
    attr_accessible :name, :post_id 
end 

class Post < ActiveRecord::Base 
    belongs_to :topic, :touch => true 
    has_many :comments, :dependent => :destroy 
    accepts_nested_attributes_for :topic 
    attr_accessible :name, :title, :content, :topic, :topic_attributes 
end 

class Comment < ActiveRecord::Base 
    has_ancestry 
    attr_accessible :name, :content 
    belongs_to  :post, :touch => true 
end 

觀點:

<%= link_to "Reply", new_post_comment_path(@post, :parent_id => comment.id) %> 

控制器:

class CommentsController < ApplicationController 
    respond_to :html, :xml 
    def show 
    @post = Post.find(params[:id]) 
    @comments = @post.comments.order("updated_at").page(params[:page]) 
    end 

    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    if @comment.save 
     flash[:notice] = "Replied to \"#{@post.title}\"" 
     redirect_to(@post) 
    else 
     flash[:notice] = "Reply failed to save." 
     redirect_to(@post) 
    end 
    end 

    def new 
    @post = Post.find(params[:post_id]) 
    @comment = Comment.new(:parent_id => params[:parent_id]) 
    # @comment = @post.comments.build 
    end 

    def destroy 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.find(params[:id]) 
    @comment.destroy 
    redirect_to post_path(@post) 
    end 
end 

通過閱讀代碼,你可能已經收集,我試圖讓ancestry寶石與嵌套資源工作。我一直在使用Acesstry gem上的Railscasts插曲來指導我。感謝您閱讀我的問題。

回答

1

試圖通過評論ID

link_to "Reply", new_post_comment_path(@post, :parent_id => comment.id). 
0

您需要使用嵌套路徑:link_to "Reply", new_post_comment_path(@post, :parent_id => comment)

rake routes可以成爲你的朋友。

+0

有了這個代碼,我得到一個路由錯誤:'沒有路由匹配{:動作=> 「新」,:控制器=> 「意見」:PARENT_ID =># <評論ID:4,名稱:「」,內容:「評論。」,post_id:33,created_at:「2011-05-11 02:35:10」,updated_at:「2011-05-11 02:35:10 「,祖先:無>}' – BasicObject 2011-05-12 00:50:40

+1

它看起來像我不小心縮短了」comment.id「到路徑幫助器中的」註釋「。 – 2011-05-16 02:17:49