通过link_to传递参数时没有路由错误

时间:2011-05-11 03:06:46

标签: ruby-on-rails controller link-to nested-resources

错误:

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 gem与嵌套资源一起使用。我一直在使用Ancestry gem上的Railscasts剧集来指导我。感谢您阅读我的问题。

2 个答案:

答案 0 :(得分:1)

尝试传递评论ID

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

答案 1 :(得分:0)

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

rake routes可以成为你的朋友。