获取Rails URL帮助程序以自动输出https URL

Joe*_*Dyk 31 ruby ssl routes ruby-on-rails

我正在开发一个混合了http和https的网站 - 最简单/最简单的方法是让链接使用正确的路由协议 - 是否可以在路由文件中指定?

假设我在Rails 3中有以下路由.

match "/test" => "test#index", :as => :test, :constraints => { :protocol => 'https' }

如果我在http页面上,并且我使用test_url()它,它将输出http://domain.com/test.我想改为https://domain.com/test.

我知道我可以使用test_url(:secure => true),但那是重复的逻辑.

我知道我可以http://domain.com/testhttps://domain.com/test,但这是一个额外的重定向,加上它在表单帖子上失败了.

想法?

Kri*_*ari 27

使用test_url(:protocol => 'https')了HTTPS URL中.

  • "我知道我可以使用test_url(:secure => true),但这是重复的逻辑." (4认同)

apn*_*ing 19

没试过,但在你的ApplicationController:

def default_url_options(options={})
 { :secure => true }
end 
Run Code Online (Sandbox Code Playgroud)

  • 好的,抱歉.备注:给试图帮助你的人提供-1不会为你的事业服务. (11认同)
  • 仍然不确定这对我有什么帮助。如果我在 http 页面上,我希望 test_url() 返回 https URL,而不是 http URL。 (2认同)
  • 可能情况发生了变化,这在5.1.4中不再起作用。参见/sf/answers/3414670031/ (2认同)

i_e*_*uel 6

def default_url_options(options={})
 { :protocol => "https" }
end
Run Code Online (Sandbox Code Playgroud)

  • 虽然这段代码可能有助于解决问题,但它没有解释_why_和/或_how_它回答了这个问题.提供这种额外的背景将显着提高其长期价值.请[编辑]您的答案以添加解释,包括适用的限制和假设. (4认同)