Search code examples
ruby-on-railsroutesnested-routes

Routing Error No Route Matches (correct route)


I'm in the process of building an edit form. I have completed the form and it renders as it should. When I go to submit the update to the form I get a no route error. The path to my edit page is for example '/topics/1/bookmarks/1/edit'. This page loads perfectly fine. That page contains a partial of the form that will be used to edit the record. When I select the submit button however it re-routes to '/topics/1/bookmarks/1' and gives me the following:

Routing Error
No route matches [PATCH] "/topics/1/bookmarks/1"

Below are the files that should be of importance let me know if there is something I did not share. That would be important to view.

bookmarks_controller.rb

def edit
  @topic = Topic.find(params[:topic_id])
  @bookmark = Bookmark.find(params[:id])
end

def update
  @topic = Topic.find(params[:topic_id])
  @bookmark = Bookmark.find(params[:id])

  if @bookmark.update_attributes(params.require(:bookmark).permit(:url, :topic_id, :description))
    flash[:notice] = "Bookmark was updated"
    redirect_to [@topic, @bookmark]
  else
    flash[:error] = "There was an error saving the Bookmark.  Please try again."
    render :edit
  end
end

config/routes.rb

resources :topics do
  resources :bookmarks, only: [:show, :new, :edit]
end

bookmarks/_form.html.erb

<%= form_for [topic, bookmark] do |f|  %>
  <%= f.label :description %>
  <%= f.text_field :description %>
  <%= f.label :url %>
  <%= f.text_field :url %>
  <%= f.submit %>
<% end %>

bookmarks/edit.html.erb

 <%= render partial: 'form', locals: {topic: @topic, bookmark: @bookmark} %>

Solution

  • You don't have an update route, which is what actually updates the database. Just change

     resources :bookmarks, only: [:show, :new, :edit] 
    

    to

    resources :bookmarks, only: [:show, :new, :edit, :update]
    

    OR better yet,

    resources :bookmarks, except: [:index, :create, :destroy] 
    

    If you have a new action, then you should want a create action too. So, finally:

    resources :bookmarks, except: [:index, :destroy]