Marcos Icaza Marcos Icaza - 2 months ago 7
Ruby Question

creating a form to route a method inside controller

I am trying to create a form that redirects to a method called accept_item on the form controller. My issue is that it's not going through the accept_item method when I submit the form.

form_controller.rb

def accept
@form = Form.find(params['id'])
end
def accept_item
redirect_to inventories_path
end


accept.html.erb

<%= form_tag accept_item_forms_url do %>
<% @form.items.each do |i| %>
<%= label_tag 'Item Name' %>
<p><%= i.name %></p>
<%= label_tag 'Quantity' %>
<p><%= text_field_tag 'quantity', i.quantity %></p>

<% end %>
<%= submit_tag 'Accept', class: 'btn btn-default btn-about pull-left', data: {confirm: 'Are you sure you want to accept?'} %>
<% end %>


routes.rb

resources :forms do
collection do
get :accept_item, :as => :accept_item
end
end


Error Message

No route matches [POST] "/forms/accept_item"

Answer

The form_tag helper uses the HTTP POST method by default. You defined your routes with get:

get :accept_item, :as => :accept_item

You should use post instead:

post :accept_item, :as => :accept_item

Also I don't think you need the as: :accept_item part, unless you're going to use accept_item_url instead of accept_item_forms_url.