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 Rspec的简单的介绍 1 安装Rspec 在Rails的配置文件Gemfile配置...
    AQ王浩阅读 27,104评论 6 28
  • Awesome Ruby Toolbox Awesome A collection of awesome Ruby...
    debbbbie阅读 2,964评论 0 3
  • 1.caching with instance variables2.dynamic find_by method...
    Jayzen阅读 1,446评论 0 1
  • 在学习rails时,我们有必要了解rails程序中的目录结构。rails对于不同的文件,不同的代码存放在什么样的文...
    vito1994阅读 6,084评论 1 17
  • 文/天涯草 有时我还会想起那段时光,想起那个叫肖雅的女孩,还有她曾经的点滴感伤。也许时值今日,她早已获得了属于她的...
    天涯草阅读 302评论 1 1