生成一个完整的资源路径,只为路由助手提供最后一个资源 [英] Generating a full resourceful path giving only the last resource to the routes helper

查看:29
本文介绍了生成一个完整的资源路径,只为路由助手提供最后一个资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之

# routes.rb
resources :article do
  resources :comments do
    resources :replies
  end
end

我希望 reply_path 生成与 article_comment_reply_path

更多详情

我想在 URL 中链接一些资源,但我不想每次都将所有这些资源都提供给帮助程序:

I have some resources that I want to chain in the URL, but I don't want to give all these resources to the helper every time:

article_comment_reply_path(@reply.comment.article, @reply.comment, @reply)
# /articles/:acticle_id/comments/:comment_id/replies/:id

相反,我想做:

reply_path(@reply)
url_for [@reply]
link_to 'View reply', @reply

但这会生成 /replies/:id

我确实在控制器级别解决了这个问题,方法是检查 :article_id:comment_id 是否已设置,如果没有,则将用户重定向到 article_comment_reply_path.但这会导致两个问题:

I did solve this on a controller level, by checking if :article_id and :comment_id are set and if not, to redirect the user to article_comment_reply_path. But this causes 2 problems:

  • Double redirect and a waste of server resources.
  • The href in the <a>element is different than the page url, so more of a hassle to determine if it's an active link.

有没有办法让 url helper 根据其父资源生成自定义路径?

Is there a way I can get the url helper to generate a custom path according to it's parent resources?

推荐答案

我想我在这里找到了你需要的东西:https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-direct

I think I found what you need here: https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-direct

direct :reply do |reply|
  [ reply.comment.article, reply.article, reply ]
end

direct :edit_reply do |reply|
  [ :edit, reply.comment.article, reply.article, reply ]
end

这篇关于生成一个完整的资源路径,只为路由助手提供最后一个资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆