How do you pass multiple arguments to nested route paths in Rails?

淺唱寂寞╮ 提交于 2019-12-07 06:09:19

问题


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?'}%>


来源:https://stackoverflow.com/questions/25269232/how-do-you-pass-multiple-arguments-to-nested-route-paths-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!