如何在lib模块中使用url helper,并为多个环境设置host

在Rails 3.2应用程序中,我需要访问lib文件中的url_helpers。 我正在使用

 Rails.application.routes.url_helpers.model_url(model) 

但我得到了

 ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true): 

我已经找到了一些关于此的内容,但没有真正解释如何在多种环境中解决这个问题。

即我假设我需要在我的development.rb和production.rb文件中添加一些东西,但是什么?

最近我看到使用config.action_mailer.default_url_option建议的答案,但这不适用于动作邮件程序之外。

为多个环境设置主机的正确方法是什么?

这是一个我一直遇到的问题,并且已经让我烦恼了一段时间。

我知道很多人会说它违反MVC架构来访问模型和模块中的url_helpers,但有时候 – 例如在与外部API接口时 – 它确实有意义。

现在感谢这篇精彩的博文,我找到了答案!

 #lib/routing.rb module Routing extend ActiveSupport::Concern include Rails.application.routes.url_helpers included do def default_url_options ActionMailer::Base.default_url_options end end end #lib/url_generator.rb class UrlGenerator include Routing end 

我现在可以在任何模型,模块,类,控制台等中调用以下内容

 UrlGenerator.new.models_url 

结果!

对安迪的可爱答案略有改善(至少对我而言)

 module UrlHelpers extend ActiveSupport::Concern class Base include Rails.application.routes.url_helpers def default_url_options ActionMailer::Base.default_url_options end end def url_helpers @url_helpers ||= UrlHelpers::Base.new end def self.method_missing method, *args, &block @url_helpers ||= UrlHelpers::Base.new if @url_helpers.respond_to?(method) @url_helpers.send(method, *args, &block) else super method, *args, &block end end end 

以及你使用它的方式是:

 include UrlHelpers url_helpers.posts_url # returns https://blabla.com/posts 

或简单地说

 UrlHelpers.posts_url # returns https://blabla.com/posts 

谢谢安迪! +1

在任何模块控制器中使用此字符串可以使应用程序URL帮助程序在任何视图或控制器中都有效。

 include Rails.application.routes.url_helpers 

请注意,一些内部模块url-helpers应该是命名空间。

示例: root应用程序

的routes.rb

 Rails.application.routes.draw do get 'action' => "contr#action", :as => 'welcome' mount Eb::Core::Engine => "/" , :as => 'eb' end 

模块Eb中的Url助手:

 users_path 

在控制器include Rails.application.routes.url_helpers中添加include Rails.application.routes.url_helpers

所以那个助手应该是

 eb.users_path 

因此,在Eb模块中,您可以使用与根应用程序中相同的welcome_path

不确定这是否适用于Rails 3.2,但在以后的版本中,设置路由的默认url选项可以直接在routes实例上完成。

例如,设置与ActionMailer相同的选项:

 Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options