How do you pass multiple arguments to nested route

2019-04-30 19:02发布

问题:

I am new to Rails and normally set up a link_to helper for a normal unnested route like so:

link_to "Delete", article_path(article.id), method: :delete, data: {confirm: "Are you sure?"}

However I am learning about nested routes and it seems I need to provide the path with two arguments for example:

link_to "(Delete)", article_comments_path(comment.article_id, comment.id), method: :delete, data:{comfirm: 'Are you sure?'}

However this does not seem to work. I have seen that you can format the link_to like this:

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

But this seems confusing to me as there is no path defined and the values necessary for the path arn't directly specified either.

Is it possible to format a nested link_to path like the unnested one above or does it need to be formatted as shown in the third example? If so could someone try to explain how this array format is translated into a url for Rails to execute?

Thanks

Route:

article_comment_path - DELETE - /articles/:article_id/comments/:id(.:format) - comments#destroy

回答1:

I think your route would be something like articles/:article_id/comments/:id so you can do:

<%= link_to "Delete", article_comments_path(article_id: comment.article_id, id: comment.id), method: :delete, data:{comfirm: 'Are you sure?'} %>

And your 3rd link should be

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

For details check Polymorphic routes

Update

You just need to pass locals to your partial like:

<%= render "comment", locals: {article: comment.article, comment: comment} %>

and then use

<%= link_to "Delete", article_comments_path(article.id,comment.id), method: :delete, data:{comfirm: 'Are you sure?'}%>