Search code examples
ruby-on-railsrubyruby-on-rails-4link-to

Deleting with link_to from within a Rails 4 view


The following Rails 4 link_to is wrong, and thus I'm unable to delete and not sure why. In this project, "bookmarks" is a nested resource under "users" so rake routes gives me:

DELETE /users/:user_id/bookmarks/:id(.:format)                        bookmarks#destroy

View:

<% @bookmarks.each do |bookmark| %>
   <%= link_to "delete", user_bookmarks_path(@user, bookmark.id), method: :delete %>
<% end %>

Controller:

def destroy
    @user.bookmarks.find(params[:id]).destroy
    redirect_to root_path
end

private

def bookmark_params
    params.require(:bookmark).permit(:title, :bookmark_url)
end

def get_user
    @user = User.friendly.find(params[:user_id])
end

The result is a link that looks like http://www.example.com/users/jane-doe/bookmarks.6 where 6 is the correct ID of the bookmark to be deleted. But I don't understand why it's not creating /bookmarks/6, which I think would then work fine with destroy in my controller. It feels like there's some big conceptual piece I'm just not understanding. Any tips are appreciated.


Solution

  • Your view should look something like this. It appears your path name is incorrect:

    <% @bookmarks.each do |bookmark| %>
       <%= link_to "delete", user_bookmark_path(@user, bookmark.id), method: :delete %>
    <% end %>