Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change protocol to https in all rails helpers

Rails 3.1+ I want my url helpers to use the https protocol without having to specify it in every helper I call. After searching around I've found various ways but none work, for example:

 ROUTES_PROTOCOL = (ENV["RAILS_ENV"] =~ /development/ ? 'http://' : 'https://')

scope :protocol => ROUTES_PROTOCOL, :path => "/app" do

How can this be done?

like image 921
99miles Avatar asked Feb 28 '12 20:02

99miles


3 Answers

If you are using Rails 4, defining ApplicationController#default_url_options doesn't work. URL options are now defined in the application's routes config:

Rails.application.routes.draw do
  default_url_options protocol: :https
end
like image 175
iloveitaly Avatar answered Nov 09 '22 20:11

iloveitaly


So you want it mainly for links in emails?

I think this will work in your production.rb, development.rb or any other environment.

config.action_mailer.default_url_options = {
  :host => 'yourwebsite.com',
  :protocol => 'https'
}

# Makes it possible to use image_tag in mails
config.action_mailer.asset_host = "https://yourwebsite.com"
like image 14
Michael Koper Avatar answered Nov 09 '22 21:11

Michael Koper


In Rails 5.1.4, I have tested the following scenarios:

# in development.rb
config.action_controller.default_url_options({:protocol => 'https'})
config.action_controller.default_url_options(:protocol => 'https')
# Does not work

# in development.rb, outside config block
Rails.application.routes.default_url_options[:protocol] = 'https'
# Does not work, but works under console

# in routes.rb
Rails.application.routes.draw do
  default_url_options protocol: :https
# Does not work, but works under console

# in ApplicationController
def default_url_options(options={})
  { secure: true }
end
# Does not work

# in ApplicationController
def default_url_options
  { protocol: :https }
end
# Works in browser, but does not work under console

# in development.rb
config.action_controller.default_url_options= {:protocol => 'https'}
# Works in browser, but does not work under console
like image 11
lulalala Avatar answered Nov 09 '22 19:11

lulalala