Search code examples
ruby-on-railsdestroy

link_to 'Destroy', [comment.article, comment],


In http://guides.rubyonrails.org/getting_started.html with rails-5.0.2 and Ruby 2.4.1

The guides use

[comment.article, comment]

Which I like to learn of how to use it, What the meaning of this. I just don't understand and can not find any document.

<%= link_to 'Destroy Comment', [comment.article, comment],
           method: :delete,
           data: { confirm: 'Are you sure?' } %>

instead of

<%= link_to 'Destroy Comment', article_comment_path,
           method: :delete,
           data: { confirm: 'Are you sure?' } %>

which is not work (including article_comment_path(comment) error shown:

ActiveRecord::RecordNotFound in CommentsController#destroy

<%= link_to 'Destroy Comment', article_comment_path(comment)

Here routes

    Prefix Verb   URI Pattern                                       Controller#Action
    article_comments GET    /articles/:article_id/comments(.:format)          comments#index
                     POST   /articles/:article_id/comments(.:format)          comments#create
 new_article_comment GET    /articles/:article_id/comments/new(.:format)      comments#new
edit_article_comment GET    /articles/:article_id/comments/:id/edit(.:format) comments#edit
     article_comment GET    /articles/:article_id/comments/:id(.:format)      comments#show
                     PATCH  /articles/:article_id/comments/:id(.:format)      comments#update
                     PUT    /articles/:article_id/comments/:id(.:format)      comments#update
                     DELETE /articles/:article_id/comments/:id(.:format)      comments#destroy
            articles GET    /articles(.:format)                               articles#index
                     POST   /articles(.:format)                               articles#create
         new_article GET    /articles/new(.:format)                           articles#new
        edit_article GET    /articles/:id/edit(.:format)                      articles#edit
             article GET    /articles/:id(.:format)                           articles#show
                     PATCH  /articles/:id(.:format)                           articles#update
                     PUT    /articles/:id(.:format)                           articles#update
                     DELETE /articles/:id(.:format)                           articles#destroy
                root GET    /                                                 articles#index

Solution

  • It's short for a nested route in Rails. When you provide link_to an array like that, it will translate into a URL such as: /articles/1/comments/2. Most just use the route helpers however since they're more explicit (ie. article_comment_path(article_id: @article.id, id: @comment.id)

    Post your controller code for the destroy method as well as any errors you're getting since you have the right routes setup.