ActionController :: RoutingError(没有路由匹配

时间:2013-02-12 12:22:51

标签: jquery ruby-on-rails ruby-on-rails-3 rails-routing

我正在尝试添加或删除嵌套的has_many对象,如下所示

class Question < ActiveRecord::Base
  has_many :comments
end

= form_for @question, :url => {:action => "create"} do |f|
  = f.label :name
  = f.text_field :name
  #comments
  = link_to 'Add Comment", add_comment_question_path, method: :get
  = f.submit

:JavaScript的

  $('#add_comment').click(function() {
    $('#comments').append("#{escape_javascript(render(:partial => "comment"))}");
  });

在我的_comment.html.haml

= fields_for @question.comments do |c|
  = c.label :msg
  = c.text_field :msg

在我的控制器中

def add_comment
   @question.comments << Comment.new
end

在routes.rb

resources :questions do
  get :add_comment, :on => :member
end

但是我在加载question/new.html.haml时收到路由错误。我还运行rake routes获取正确的指定网址。为什么我收到这个错误?

3 个答案:

答案 0 :(得分:1)

我假设错误在add_comment_question_path。此命名路由需要将问题资源传递给它add_comment_question_path(@question)。但是,由于您尝试以相同的形式创建@question,因此在您的情况下仍然无效。

答案 1 :(得分:0)

你试过了吗?

= form_for @question, :url => questions_path do |f|
应该questions_path自动生成

routes.rb。这些可以通过运行rake routes来枚举,该route_path显示可以通过route_url或{{1}}引发的可用路线。

HTH

答案 2 :(得分:0)

尝试添加发布方法:

form_for(@question, :url => {:action => "create"}, :html => {:method => "post"} ) do |f|

将routes.rb编辑为:

在routes.rb

resources :questions do
   member do
     get :add_comment
   end
end