【问题标题】:Routing error: No route matches [POST]路由错误:没有路由匹配 [POST]
【发布时间】:2013-12-22 05:07:32
【问题描述】:

我正在尝试使用 form_tag 构建一个用餐小费计算器,但我的表单提交会产生路由错误。我花了一个小时搜索,但无法弄清楚。

错误:没有路由匹配 [POST] "/tips"

我的路线

Tips::Application.routes.draw do
  root "tips#calculate"
  get "tips/calculate"
  post "tips/calculate"
end

控制器:

class TipsController < ApplicationController
  def calculate
    @tip = params[:price].to_i * params[:tip].to_i
    render 'calculate'
  end
end

查看:

<h1>Enter your meal info</h1>
<p>Find me in app/views/tips/calculate.html.erb</p>
<%= form_tag('/tips#calculate') do %>
<p>
    <%= label_tag("Meal price:") %>
    <%= text_field_tag(:price, nil, placeholder: "Enter cost without tax and tip")%>
</p>
<p>
    <%= label_tag("Tip:") %>
    <%= text_field_tag(:tip, nil, placeholder: "Enter tip (i.e. 15 for 15%)") %>
</p>
<p>
    <%= submit_tag 'Calculate!' %>
</p>
<p>
    <%= label_tag("Tip value:") %>
    <%= text_field_tag("tip", @tip, precision: 2, :readonly => true) %> #this probably needs to be changed
<% end %>

耙路线:

$ rake routes
        Prefix Verb URI Pattern               Controller#Action
          root GET  /                         tips#calculate
tips_calculate GET  /tips/calculate(.:format) tips#calculate
               POST /tips/calculate(.:format) tips#calculate

【问题讨论】:

    标签: ruby-on-rails routing


    【解决方案1】:

    在您的路由文件中,您已在 /tips/calculate/ 声明了 POST 请求的端点。但是,在您的表单中,您正尝试 POST 到 /tips#calculate。浏览器将#calculate 视为一个片段(又名命名锚),并且不会将其发送到服务器。

    将您的form_tag 更改为form_tag('/tips/calculate'),该错误应该会消失。

    【讨论】:

    • 混淆可能源于#的不同含义。在路由列表中,tips#calculate 表示“TipsController 类中的calculate 方法”,而 URL 中的# 是一个片段。
    • 是的,这解决了它!干杯,太新了,不能投票。在相关的注释中,guides.rubyonrails.org/form_helpers.html 表示 form_tag 应该能够成为 &lt;%= form_tag('form_calculate_path') do %&gt; 但这也会引发错误。有人知道(更好的)form_tag 示例/文档吗?
    • 您应该可以使用form_tag(tips_calculate_path) ... 。您在rake routes 的输出中看到prefix 列?您可以将_path_url 附加到该名称以分别获取路径(从根...通常是/)或url(如example.com/path/goes/here)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多