user2936314
user2936314

Reputation: 1792

Routing error: No route matches [POST]

I am trying to build a meal tips calculator using form_tag and my form submissions generate a routing error. I spent an hour searching, but can't figure it out.

Error: No route matches [POST] "/tips"

My routes

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

Controller:

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

View:

<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:

$ 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

Upvotes: 0

Views: 281

Answers (1)

Zajn
Zajn

Reputation: 4088

In your routes file, you have declared an endpoint for POST requests at /tips/calculate/. In your form, however, you're trying to POST to /tips#calculate. The browser sees that #calculate as a fragment (aka a named anchor), and doesn't send that to the server.

Change your form_tag to read form_tag('/tips/calculate') and that error should go away.

Upvotes: 1

Related Questions