开发者

No Route error when passing parameters through link_to

开发者 https://www.devze.com 2023-03-04 19:58 出处:网络
Error: No route matches {:action=>\"new\", :controller=>\"comments\", :parent_id=>1} routes.rb:

Error:

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

models:

class Topic < ActiveRecord::Base
  has_many        :posts, :dependent => :des开发者_运维知识库troy
  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

view:

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

controller:

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

By reading the code you might have gathered that I am trying to get the ancestry gem to work with nested resources. I've been using the Railscasts episode on the Ancestry gem to guide me. Thanks for reading my question.


Try to pass comment id

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


You need to use the nested path: link_to "Reply", new_post_comment_path(@post, :parent_id => comment).

rake routes can be your friend.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号