Нет ошибки маршрута при передаче параметров через link_to

#ruby-on-rails #controller #link-to #nested-resources

#ruby-on-rails #контроллер #ссылка на #вложенные ресурсы

Вопрос:

Ошибка:

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 работать с вложенными ресурсами. Я использовал эпизод Railscasts в Ancestry gem, чтобы руководствоваться им. Спасибо, что прочитали мой вопрос.

Ответ №1:

Попробуйте передать идентификатор комментария

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

Ответ №2:

Вам нужно использовать вложенный путь: link_to "Reply", new_post_comment_path(@post, :parent_id => comment) .

rake routes может быть вашим другом.

Комментарии:

1. С этим кодом я получаю ошибку маршрутизации: No route matches {:action=>"new", :controller=>"comments", :parent_id=>#<Comment id: 4, name: "", content: "commented.", post_id: 33, created_at: "2011-05-11 02:35:10", updated_at: "2011-05-11 02:35:10", ancestry: nil>}

2. Похоже, я случайно сократил «comment.id «для «комментария» в помощнике path.