Ruby-on-rails Rails,获取模型中的资源路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5380703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:44:00  来源:igfitidea点击:

Rails, get resource path in model

ruby-on-railsresources

提问by jonepatr

How do I get the path to a resource in the model? I need to store it in the database and would like the same url as you get from resourcename_path(resource)

如何获取模型中资源的路径?我需要将它存储在数据库中,并希望与您从 resourcename_path(resource) 获得的网址相同

回答by hrdwdmrbl

In Rails 3 and Rails 4 you can use:

在 Rails 3 和 Rails 4 中,您可以使用:

Rails.application.routes.url_helpers

e.g.

例如

Rails.application.routes.url_helpers.posts_path

回答by idlefingers

In Rails 3, you can include the url helpers in models (though it normally is not the best way of dealing with things):

在 Rails 3 中,您可以在模型中包含 url 助手(尽管这通常不是处理事情的最佳方式):

class MyClass < ActiveRecord::Base
  include Rails.application.routes.url_helpers
end

In Rails 2, I think it's include ActionController::UrlWriter, but I can't remember. Google is your friend.

在 Rails 2 中,我认为是include ActionController::UrlWriter,但我不记得了。谷歌是你的朋友。