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

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

问题描述

说我有一个名为Thing的Rails模型.事物具有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、4和5中,您可以使用:

In Rails 3, 4, and 5 you can use:

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天全站免登陆