【问题标题】:Why am I receiving a routing error when the controller method exists, the route is defined and the view calls it?为什么当控制器方法存在、路由已定义并且视图调用它时,我会收到路由错误?
【发布时间】:2011-10-09 02:07:01
【问题描述】:

我有一个简单的购物车应用程序,它在应用程序布局的侧边栏上显示会话的购物车,其中包含 line_items。我正在尝试在每个行项目的末尾添加一个按钮(在 _line_item.html.erb 中呈现),该按钮使用 remote: true 和一些 JS 将购物车中的数量减少一个。但是,当我加载页面时(在单击任何内容之前),我在开发中收到来自 Rails 3.1 的路由错误,没有安装特殊的 gem 或配置:

   Routing Error

    No route matches {:action=>"decrement", :controller=>"line_items"}

这是我在 controllers/line_items_controller.rb 中的方法,到目前为止它对我来说一直运行良好:

  def decrement
    @line_item = LineItem.find(params[:id])
    @line_item.quantity -= 1
    if @line_item.quantity.empty?
      @line_item.destroy
    end 

    respond_to do |format|
      format.js {@current_item = @line_item}
    end
  end

这是 routes.rb 中的入口:

  resources :line_items do
    member do
      post 'decrement'
    end
  end

这是部分 _line_item.html.erb 中的代码,没有 button_to 链接也可以正常工作:

<% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
    <td><%= line_item.quantity %>&times;</td>
    <td><%= line_item.product.title %></td>
    <td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
    <td><%= button_to 'Remove one', line_item, decrement_line_item_path, remote: true %></td>
</tr>

我一定错过了什么,但我找不到。似乎一切都是为了我。我究竟做错了什么?非常感谢。

编辑:这是我使用 decrement_line_item_path(line_item) 时收到的错误:

ArgumentError in Store#index

Showing /Users/Michael/Sites/rails/depot/app/views/line_items/_line_item.html.erb where line #9 raised:

wrong number of arguments (4 for 3)
Extracted source (around line #9):

6:  <td><%= line_item.quantity %>&times;</td>
7:  <td><%= line_item.product.title %></td>
8:  <td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
9:  <td><%= button_to 'Remove one', line_item, decrement_line_item_path(line_item), remote: true %></td>
10: </tr>

【问题讨论】:

  • 运行 rake 路由会得到什么?您不必发布整个内容,只需发布​​与此资源相关的部分
  • decrement_line_item POST /line_items/:id/decrement(.:format) {:action=>"decrement", :controller=>"line_items"}
  • 对于以后在谷歌上搜索的人:这个错误也经常是由请求方法,GET,PUT,POST等引起的。如果你使用get 'posts',你会得到一个“No Route例如,如果您尝试 PUT 到帖子,则匹配...”错误。
  • 是的,我还应该补充一点,我只是没有在 button_to 中列出该方法,因为 Rails 默认为 post。

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


【解决方案1】:

decrement_line_item_path 需要单个项目的参数,而您没有给它一个参数。

试试:

<%= button_to 'Remove one', decrement_line_item_path(line_item), remote: true %>

【讨论】:

  • 我完全按照您的方式进行了尝试并得到了这个错误:ArgumentError in Store#index Showing /Users/Michael/Sites/rails/depot/app/views/line_items/_line_item.html.erb where第 9 行引发:参数数量错误(4 对 3)提取的源(在第 9 行附近):6:× 7: 8: 9: 10:
  • 我编辑了这个问题,因为评论中的代码很难阅读。
  • 那是因为您没有使用我的代码,您仍然将 line_item 作为单独的参数传递。 button_to 只需按 labelpathoptions 的顺序排列即可。您正在传递 line_item 它甚至不应该存在的地方。
  • 哦,真的很抱歉。你说的对。我没有看到区别。现在可以使用了!
猜你喜欢
  • 2022-12-20
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
相关资源
最近更新 更多