美文网首页Ruby
Rails在Model中使用routes helper

Rails在Model中使用routes helper

作者: qingxp9 | 来源:发表于2015-10-29 14:22 被阅读347次

在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

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

  • Everyday-rails-rspec - 模型测试

    简单的测试文件 测试文件model: *** 在每个测试文件的开头是:require 'rails_helper'...

  • 应该是一个被自己一直忽略的常识

    rails的过程是先走到routes、然后去对应的controller找相应的action方法、再去model(如...

  • [Rails] Routes

    1. 是什么 Routes 的存在是为了匹配请求中的URL和定义的controller#action.让我来简单地...

  • rails 笔记

    Rails 入门Ruby on Rails 教程 需要 手动 安装依赖 使用脚手架 生成model rake 命令...

  • Rails 常用命令

    ruby on rails 新建model和controller rails generate model mod...

  • rails常用helper之number

    rails中 几个重要的关于number 的helper 1. number_to_currency Softwa...

  • rails 路由学习1

    rails config/routes.rb 指定路由的代码如下 上面的代码定义了5种风格的路由,rails在启动...

  • Rails中的Helper方法

    tag类的Helper form_tag 复选框 单选框 处理模型对象 Hash 数组 Hash和数组结合 for...

  • rails 笔记(2)

    rails中的校验和测试 1、model 文件中增加validates,validates方法是个标准的Rails...

网友评论

    本文标题:Rails在Model中使用routes helper

    本文链接:https://www.haomeiwen.com/subject/juqfhttx.html