我正在尝试使用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
答案 0 :(得分:1)
在您的路线文件中,您已在/tips/calculate/
为POST请求声明了一个端点。但是,在您的表单中,您尝试POST到/tips#calculate
。浏览器将#calculate
视为片段(也称为命名锚点),并且不会将其发送到服务器。
将您的form_tag
更改为form_tag('/tips/calculate')
,该错误应该消失。