如何在Rails 3的模型中使用路由助手?

Flo*_*nt2 22 routing model ruby-on-rails-3

在模型回调中,我进行API调用,并且需要为API提供一些URL.这些URL很容易由路由助手生成.

在这个答案 中给出的解决方案在Rails 3中不再起作用.

有解决方案吗 谢谢 :)

Flo*_*nt2 30

Got an answer from the rails IRC: just add

  include Rails.application.routes.url_helpers
Run Code Online (Sandbox Code Playgroud)

to your model

  • 这可能会导致无限循环错误.如果你这样,你可以使用委托,即`delegate:url_helpers,来:'Rails.application.routes'. (3认同)

hrd*_*rbl 17

在Rails 3中,您可以使用:

Rails.application.routes.url_helpers
Run Code Online (Sandbox Code Playgroud)

例如

Rails.application.routes.url_helpers.posts_path
Run Code Online (Sandbox Code Playgroud)