Rails在Model中使用routes helper

在View中我们可以调用routes的帮助方法得到路径地址
比如下面代码的search_path

<%= form_tag search_path , method: 'get'  do %> 
---
<%= end %>

如果想在 Model 中使用这个helper该怎么做呢?

中文网页中果然搜不到,终于还是在stackoverflow上找到了答案
整理摘录如下:

在Rails 3 和4 中调用

Rails.application.routes.url_helpers

比如

Rails.application.routes.url_helpers.posts_path
Rails.application.routes.url_helpers.posts_url(:host => "example.com")

为方便使用我们可以直接include这个模块

Rails.application.routes.url_helpers 

不过相比于include整个模块,更推荐delegate

delegate :url_helpers, to: 'Rails.application.routes' 
url_helpers.users_url => 'www.foo.com/users'

http://stackoverflow.com/questions/341143/can-rails-routing-helpers-i-e-mymodel-pathmodel-be-used-in-models

你可能感兴趣的:(Rails在Model中使用routes helper)