I'm sending out an e-mail message to new users of my service. I want
to send a particular link in this e-mail but I can't figure out how to
get a complete URL from the url_for method. Is there a way to do this
without manually setting the host name?
Missing host to link to! Please provide :host parameter or set default_url_options[:host]
I can pass in the host name, but then when I deploy my production
environment I'll have to remember to go in and change it. I'm looking
around now to see if there's a way to set it just once (maybe in the
environment file).
If there's a way Rails can just figure it out, though, that would be
ideal. Are there global variables I can access, maybe, that I could
use to build out the beginning of the URL (the host name and the
application's path)?
If the problem is that your mailer isn't running as a "request", then why don't you set a variable in your config/environments/development.rb (and perhaps also in your production.rb) to get the host where you need it.
Missing host to link to! Please provide :host parameter or set default_url_options[:host]
I can pass in the host name, but then when I deploy my production
environment I'll have to remember to go in and change it. I'm looking
around now to see if there's a way to set it just once (maybe in the
environment file).
I had the same problem as you. In the mailer you cannot get the host,
because mailer is something belonging to a model, so it’s out of the
request/response cycle because of design (that’s the way to go with
MVC).
You are right that you need to pass the host parameter to your mailer,
but in some cases you won’t need to put it on the configuration file.
If the mailer gets called from a controller (as a result of one action
of the user, for example) then you can just use
“#{request.protocol}#{request.host_with_port}” and you’ll get the url
for the root of your application.
Unfortunately, if you are going to invoke the mailer from a cron or a
task, then there’s no request and you should stick to the configuration
constant solution.
Yes, the code that sens the mail message in an Mailer object, it's
outside the request/response cycle so it's request object is always
nil. I was thinking about putting this information in the environment
somewhere, but then I'd have to change it at deployment time and that
would be kind of a drag.
Passing the request object to the Mailer from the calling Controller
is a good idea! I hadn't thought of that, that will solve this
problem, I think.