【问题标题】:ActionController::RoutingError (No route matchesActionController::RoutingError(没有路由匹配
【发布时间】:2013-02-12 12:22:51
【问题描述】:

我正在尝试添加或删除嵌套的 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 获取正确的指定网址。为什么会出现这个错误?

【问题讨论】:

  • 你可以编辑你的问题的html代码吗?
  • 指定您遇到的路由错误。没有路线匹配什么?

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


【解决方案1】:

我假设错误在add_comment_question_path 中。这个命名路由需要一个问题资源来传递给它,比如add_comment_question_path(@question)。但这仍然不适用于您的情况,因为您正在尝试以相同的形式创建 @question

【讨论】:

    【解决方案2】:

    你试过了吗:

    = form_for @question, :url => questions_path do |f|
    

    questions_path 应该从routes.rb 自动生成。这些可以通过运行rake routes 来枚举,它显示了可用的路由,然后可以使用route_pathroute_url 调用。

    HTH

    【讨论】:

      【解决方案3】:

      尝试添加方法来发帖:

      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
      

      【讨论】:

        猜你喜欢
        • 2015-10-13
        • 2016-08-25
        • 2018-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        相关资源
        最近更新 更多