How to dynamically call routes helper in rails?

若如初见. 提交于 2019-12-03 08:16:23

问题


For example, I have constructed a string called "new_work_path", now I want to call that helper as a method.

I've tried send("new_work_path", vars) and calling the same send from many objects. But I don't think that I've found the right object to call these helpers.

To do object.send("new_work_path", vars), what object should I be looking for?

I've tried to look for this online for a while but couldn't find anything. If anyone can shine some lights on this one, it would be great!

Thanks!


回答1:


try Rails.application.routes.url_helpers.send(...)

Edit:

As Larry Gebhardt mentioned the url_helpers module is no longer being cached.

Another workaround would be:

cached_helpers = Class.new do
  include Rails.application.routes.url_helpers
  include Rails.application.routes.mounted_helpers
end.new

cached_helpers.send(...)



回答2:


My bad, as per @tadman suggested, I tried to use send(:new_work_path, args) again and it worked! Must have mistyped it before.

Before finding out that send works right away, I had found another solution which is also of interest:

new_polymorphic_path(Work, args)

Which seems to offer some syntactic sugar as well.



来源:https://stackoverflow.com/questions/9596168/how-to-dynamically-call-routes-helper-in-rails

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