Search code examples
ruby-on-railsrubyformsroutesrails-routing

Form with custom url keeps submitting to Create method


I'm trying to build a simple form that passes a few params to a controller.

Here's what I have:

<%= form_tag({url: order_pizza_path}, method: :post) do %>
  <%= hidden_field_tag :id, value: 0, name:"tag-1" %>
  <!-- hidden field is then filled in with js -->
  <%= submit_tag "Submit" %>
<% end %>

<!-- routes: -->
get 'pizza/new' => 'pizza#new', as: 'new_pizza'
post 'pizza' => 'pizza#create', as: 'create_pizza'
post 'order_pizza' => 'pizza#order', as: 'order_pizza'

But when I submit, it keeps trying to point to the Create method in my Pizza controller. I keep getting the following error:

ActionController::ParameterMissing in PizzaController#create
param is missing or the value is empty: pizza

The form's url is /pizza. This is the url of the error: /pizza?method=get&url=%2Forder_pizza


This happens even if I change it to a GET request not POST. Why does my browser keep trying to go to the Create method?


Solution

  • The correct syntax is

    form_tag(order_pizza_path, method: :post)
    

    not

    form_tag({url: order_pizza_path}, method: :post)
    

    {url: order_pizza_path} is not a valid url_for_options so the form_tag will submit to the default, which is the create action.

    A valid value for url_for_options would be

    {action: 'order'}