如何在Rails中覆盖路由路径助手? [英] How to override routes path helper in rails?
本文介绍了如何在Rails中覆盖路由路径助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的路线是这样定义的
match '/user/:id' => 'user#show', :as => :user
如果由于某种原因传递了nil ID,我希望路由助手仅返回'# ',如果ID不为零,我希望它返回正常路径,例如'/ user / 123'。
还是有更好的方法来做到这一点。
这个路由助手已经在我的代码中很多地方使用过,所以我不想更改它。相反,我正在寻找一个将影响所有user_path实例的地方。
If for some reason a nil ID is passed I want the route helper to return only '#' and if ID is not nil i want it to return normal path like '/user/123'. or is there any better way to do it. this route helper has been used in lot of places in my code so I dont want to change that. Instead I am looking for one place which will effect all instances of user_path.
谢谢
推荐答案
module CustomUrlHelper
def user_path(user, options = {})
if user.nil?
"#"
else
super
end
end
end
# Works at Rails 4.2.6, for older versions try http://stackoverflow.com/a/31957323/474597
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)
这篇关于如何在Rails中覆盖路由路径助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文