An error raise when i try to update the model. spot
No route matches [PATCH] "/spots.7"
i use Rails 6, bootstrap and the gem simple_form
i've created manualy the config/routes.rb
and the form is comon to new.html.erb
and edit.html.erb
routes
index GET /spots(.:format) spots#index
new GET /spots/new(.:format) spots#new
spots POST /spots(.:format) spots#create
edit GET /spots/show/:id/edit(.:format) spots#edit
update PATCH /spots/:id(.:format) spots#update
show GET /spots/show/:id(.:format) spots#show
delete DELETE /spots/:id(.:format) spots#destroy
Controller
class SpotsController < ApplicationController
before_action :set_spot, only: [:show, :destroy, :edit, :update]
def index
@spots = Spot.all
end
def show
end
def new
@spot = Spot.new
end
def create
@spot = Spot.new(spot_params)
@spot.save
redirect_to index_path
end
def edit
end
def update
@spot.update(spot_params)
redirect_to index_path
end
def destroy
@spot.destroy
redirect_to index_path
end
private
def spot_params
params.require(:spot).permit(:name, etc...)
end
def set_spot
@spot = Spot.find(params[:id])
end
end
view - edit.html.erb
<div class="container">
<h1>FORM</h1>
<%= render "form", spot: @spot %>
</div>
the partial _form
#HERE, i think, it come from this underline, the url passed as argument is bad
<%= simple_form_for (spot), url:(spot.new_record? ? spots_path : spots_path(spot)) do |f| %>
<%= f.input :name %>
.
.
.
<%= f.submit %>
<% end %>
i've tried multiples things. Simple_form_for action hitting wrong URL on edit in rails
Path helpers generate paths with dots instead of slashes
Rails creating malformed routes with dots
the singularisation spot_path(spot)
give me an error too.
i think, i'm close but i can't see my error!
Many thanks
Your mistake is in your path helper:
spots_path
is generating the route to spots#index
so "/spots"
. If you give an argument to it like so: spots_path(spot)
all the path helper method can do is append it to the path, therefore it generates "/spots.10"
.
If you're generating the 7 CRUD (create, read, update, destroy) routes in Rails, you should use resources :spots
in routes.rb
and not do it manually. This will also generate the right prefixes for the path helper which you can find when you use the command rails routes
in your terminal.
On top of that: The routes you created are not entirely correct, show
is just spots/:id
for example (same for edit). But I guess this didn't work (it's because if you create the routes manually, the show route needs to be defined above the new route or it will confuse it with new).
As for the form, you do not need to create the url by hand, Rails' form helpers take care of generating the right route depending if the record is new or not, so just <%= simple_form_for (spot) do |f| %>
will suffice.