ruby-on-rails – 如何使用lib目录中的文件中的路由助手方法?

我需要使用lib文件夹中文件中定义的方法的root_url方法.那可能吗?

我试着把这一行包括在我的课上:

include Rails.application.routes.url_helpers

但这给我错误

Missing host to link to! Please provide :host parameter or set default_url_options[:host]

编辑:我发现如果我首先初始化路由,它是有效的:

def initialize_routes
  if Rails.env.development? || Rails.env.test?
    Rails.application.routes.default_url_options[:host] = 'localhost:3000' 
  elsif Rails.env.production?
    Rails.application.routes.default_url_options[:host] = 'example.com'
  end
end

有没有更好的方法来完成这个?也许在配置文件中设置路由?

解决方法

应该有几个解决方案.

1)当在主机参数中使用root_url pass时,如下所示:

root_url(:host => 'localhost')

然而,这需要做出具体的环境.

2)您也可以设置路由default_url_options,如:

Rails.application.routes.default_url_options[:host]= 'localhost:3000'

3)在您的环境配置文件中,您应该按照错误中的说明设置default_url_options.例如:

在config / environments / development.rb中:

config.action_mailer.default_url_options[:host] = 'localhost'

在config / environments / test.rb中:

config.action_mailer.default_url_options[:host] = 'localhost'

在config / environments / production.rb中:

config.action_mailer.default_url_options[:host] = 'production.com'

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...