【问题标题】:Rails routes and controller actionsRails 路由和控制器操作
【发布时间】:2014-09-24 07:33:00
【问题描述】:

在我的控制器中,我有 -

def remove_file
  @chap_comment.remove_chap_comment_pdf!
  @chap_comment.save
end

...在我看来,我有 -

<%= link_to 'remove pdf', controller: 'chap_comments', action: 'remove_file', id: comment.id %>

...在 routes.rb 我只是有 -

资源:chap_cmets

...但是在带有链接的页面甚至呈现之前我得到No route matches {:action=&gt;"remove_file", :controller=&gt;"chap_comments", :id=&gt;1} - 我应该在我的路线中放什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 routes


    【解决方案1】:

    尝试使用member

      resources :chap_comments do
        member do
          delete 'remove_file'
        end
      end
    

    这会为remove_file 添加一个额外的资源路径。完整路径为remove_file_chap_comment_path

    【讨论】:

    • get 'remove_file' 似乎有效,但 delete 无效,或者至少不适合我 - 我应该编辑答案吗?
    • 您可以使用任何您喜欢的 HTTP 动词,但看起来您的 remove_file 操作正在尝试删除某些内容,因此理想情况下您应该使用 DELETE。你试过用remove_file_chap_comment_path(id)调用路由吗?
    • 我得到了No route matches [GET] "/chap_comments/id/remove_file"',所以我认为它期待得到。我使用的link_to 是link_to 'remove pdf', remove_file_chap_comment_path(:id)
    • 尝试为您的link_to 提供:method =&gt; :delete 选项。如果您不指定,它将默认为 GET
    • 谢谢汤姆。这正确调用了动作,但出于兴趣,rails 对 delete 方法做了什么?
    【解决方案2】:

    您需要在您的路由文件中为 remove_file 添加路由。如下:

    get "chap_comments/:id/remove_file" => 'chap_comments#remove_file'
    

    【讨论】:

      【解决方案3】:

      改变你的路线,比如

      resources :chap_comments do
        member do
          delete :remove_file
        end
      end
      

      然后你可以做一个链接(运行rake routes查看方法的完整路径名)

      = link_to "Remove PDF", remove_file_chap_comment_path(id), :method => :delete
      

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 2011-09-25
        • 1970-01-01
        • 2012-08-01
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-12
        相关资源
        最近更新 更多