PudparK PudparK - 4 months ago 10
Ruby Question

Rails: No route matches [POST] "/specials/1"

This is the error I'm getting:

No route matches [POST] "/specials/1"


I understand that it's not able to produce the post route, or it isn't available.

Here's my view/form code:

<%= form_for(:special, :url => {:action => 'update', :id => @special.id}) do |f| %>

<table class="table table-responsive table-striped table-condensed table-hover" summary="Special form fields">
<tr>
<th>Order</th>
<td><%= f.text_field :order, class: "form-control" %></td>
</tr>
<tr>
<th>Name</th>
<td><%= f.text_field :name, class: "form-control" %></td>
</tr>
<tr>
<th>Description</th>
<td><%= f.text_field :description, class: "form-control" %></td>
</tr>
<tr>
<th>Fine Print</th>
<td><%= f.text_field :fine_print, class: "form-control" %></td>
</tr>
<tr>
<th>Active</th>
<td><%= f.text_field :active, class: "form-control" %></td>
</tr>
</table>

<div class="form-buttons">
<%= submit_tag("Update Special") %>
</div>

<% end %>


Heres's my controller code:

class SpecialsController < ApplicationController

def index
@specials = Special.sorted
end

def show
@special = Special.find(params[:id])
end

def new
@special = Special.new
end

def create
#Instantiation of object using form parameters
@special = Special.new(special_params)
#Save the object
if @special.save
#If success, redirect to index action
redirect_to(:action => 'index')
else
# Redisplay the form so user can fix problems
render('new')
end
end

def edit
@special = Special.find(params[:id])
end

def update
#Find an existing object using form parameters
@special = Special.find(params[:id])
#Update the object
if @special.update_attributes(special_params)
#If succeeds, redirect to index action
redirect_to(:action => 'show', :id => @special.id)
else
# If update fails, redisplay the form so user can fix problems
render('edit')
end
end

def delete
end

private
def special_params
params.require(:special).permit(:name, :description, :fine_print, :active, :order)
end

end


I noticed that there is an update path:

PATCH /specials/:id(.:format) specials#update


I can't figure out why the post route isn't being applied. It's looking for the right @special instance, but it doesn't seem to have the route available. Any advice?

Answer

Usually when updating a record, we do a patch request to the route. Your form should look like this:

<%= form_for(@special) do |f| %>

Rails will determine the correct route is PATCH /specials/:id based on the fact that @special has been persisted to the database.

If you decide to use this same form as a partial in your new view, just make sure to add this to your controller:

def new
  @special = Special.new
end

That way whether you are on the new route or the edit route, there will always be a @special object for form_for to infer whether to POST to /specials or PATCH /specials/:id