Home > Enterprise >  Rails Nested Route: Delete action doesn't work for nested resource when displaying parent resou
Rails Nested Route: Delete action doesn't work for nested resource when displaying parent resou

Time:12-11

I have a database with people and nicknames, nicknames are nested resources to people.

All works fine except one thing: I am displaying a list of nicknames on the "show" page for people - next to them, I have a little link that says "delete". However I cannot delete them - I get an error as follows:

Couldn't find Person with 'id'=44
  def load_person
    @person = Person.find(params[:person_id])
  end

The load_person method is defined in the nicknames_controller as

before_action :load_person

def load_person
  @person = Person.find(params[:person_id])
end

Here's the destroy method from nicknames_controller.rb:

  def destroy
    @nickname.destroy
    respond_to do |format|
      format.html { redirect_to @person, notice: "Nickname was successfully destroyed." }
      format.json { head :no_content }
    end
  end

Here's the view snippet of views/persons/show.html.erb:

<% @person.nicknames.each do |aka| %>
  <li>
    <%= link_to nickname.display_name, edit_person_nickname_path(@person, aka) %>
    <%= link_to '', person_nickname_path(aka), method: :delete, data: { confirm: 'Are you sure?' }, class: "far fa-trash-alt text-error", title: "Remove" %>
  </li>
<% end %>

So the route to "delete" is something like

http://127.0.0.1:3000/persons/44/nicknames/15

WHen I display the nickname (show method) and delete from there (same route as above), everything works fine.

What am I overlooking?

CodePudding user response:

ok - so as simple as it was stupid. the delete link had the wrong path - it should be

<%= link_to '', person_nickname_path(@person, aka) .... %>

but I had

..person_nickname_path(aka) ...
  • Related