可以在模型中使用 Rails 路由助手(即 mymodel_path(model))吗? [英] Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

查看:30
本文介绍了可以在模型中使用 Rails 路由助手(即 mymodel_path(model))吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 Thing 的 Rails 模型.Thing 有一个 url 属性,可以可选地设置为 Internet 上某个位置的 URL.在视图代码中,我需要执行以下操作的逻辑:

Say I have a Rails Model called Thing. Thing has a url attribute that can optionally be set to a URL somewhere on the Internet. In view code, I need logic that does the following:

<% if thing.url.blank? %>
<%= link_to('Text', thing_path(thing)) %>
<% else %>
<%= link_to('Text', thing.url) %>
<% end %>

视图中的这种条件逻辑很丑陋.当然,我可以构建一个辅助函数,它将视图更改为:

This conditional logic in the view is ugly. Of course, I could build a helper function, which would change the view to this:

<%= thing_link('Text', thing) %>

这解决了冗长的问题,但我真的更喜欢模型本身的功能.在这种情况下,视图代码将是:

That solves the verbosity problem, but I would really prefer having the functionality in the model itself. In which case, the view code would be:

<%= link_to('Text', thing.link) %>

这显然需要模型上的链接方法.以下是它需要包含的内容:

This, obviously, would require a link method on the model. Here's what it would need to contain:

def link
  (self.url.blank?) ? thing_path(self) : self.url
end

就问题而言,thing_path() 是模型代码中的未定义方法.我假设可以将一些辅助方法引入"到模型中,但是怎么做呢?路由仅在应用程序的控制器和视图层运行是否有真正的原因?我可以想到很多模型代码可能需要处理 URL(与外部系统集成等)的情况.

To the point of the question, thing_path() is an undefined method inside Model code. I'm assuming it's possible to "pull in" some helper methods into the model, but how? And is there a real reason that routing only operates at the controller and view layers of the app? I can think of lots of cases where model code may need to deal with URLs (integrating with external systems, etc).

推荐答案

在 Rails 3 及更高版本中:

In Rails 3 and higher:

Rails.application.routes.url_helpers

例如

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

这篇关于可以在模型中使用 Rails 路由助手(即 mymodel_path(model))吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆