Rails在 Model 中使用 routes helper

来源:互联网 时间:1970-01-01

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

Vim

&lt;%= form_tag search_path , <span class="hljs-symbol" style="color: #cb4b16;">method:</span> <span class="hljs-string" style="color: #2aa198;">'get'</span> <span class="hljs-keyword" style="color: #859900;">do</span> %&gt; ---&lt;%= <span class="hljs-keyword" style="color: #859900;">end</span> %&gt; <%=form_tagsearch_path,<spanclass="hljs-symbol"style="color: #cb4b16;">method:</span><spanclass="hljs-string"style="color: #2aa198;">'get'</span> <spanclass="hljs-keyword"style="color: #859900;">do</span>%>---<%=<spanclass="hljs-keyword"style="color: #859900;">end</span>%>

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

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

在Rails 3 和4 中调用

Vim

<span class="hljs-tag" style="color: #859900;">Rails</span><span class="hljs-class">.application</span><span class="hljs-class">.routes</span><span class="hljs-class">.url_helpers</span> <spanclass="hljs-tag"style="color: #859900;">Rails</span><spanclass="hljs-class">.application</span><spanclass="hljs-class">.routes</span><spanclass="hljs-class">.url_helpers</span>

比如

Vim

Rails.application.routes.url_helpers.posts_pathRails.application.routes.url_helpers.posts_url(:host =&gt; <span class="hljs-string" style="color: #2aa198;">"example.com"</span>) Rails.application.routes.url_helpers.posts_pathRails.application.routes.url_helpers.posts_url(:host=><spanclass="hljs-string"style="color: #2aa198;">"example.com"</span>)

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

Vim

<span class="hljs-tag" style="color: #859900;">Rails</span><span class="hljs-class">.application</span><span class="hljs-class">.routes</span><span class="hljs-class">.url_helpers</span> <spanclass="hljs-tag"style="color: #859900;">Rails</span><spanclass="hljs-class">.application</span><spanclass="hljs-class">.routes</span><spanclass="hljs-class">.url_helpers</span>

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

Vim

<span class="hljs-keyword" style="color: #859900;">delegate</span> :url_helpers, to: <span class="hljs-string" style="color: #2aa198;">'Rails.application.routes'</span> url_helpers.users_url =&gt; <span class="hljs-string" style="color: #2aa198;">'www.foo.com/users'</span> <spanclass="hljs-keyword"style="color: #859900;">delegate</span>:url_helpers,to:<spanclass="hljs-string"style="color: #2aa198;">'Rails.application.routes'</span>url_helpers.users_url=><spanclass="hljs-string"style="color: #2aa198;">'www.foo.com/users'</span>

来源:

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


相关阅读:
Top