skyporter
skyporter

Reputation: 897

RuntimeError default_url_options host and root_url (with subdomain)

Each user of my app have a custom url (through subdomain) stored in db.

My request is simple, I would like to send the "user url" through a json feed, like this:

{user_name: "vincent", :user_url: "vincent.my_app.com"}

to do that I have overwrite the as_json function of user model:

def as_json(options={})
    {
        :user_name: self.name,
        :user_url: root_url(:subdomain => self.subdomain)
    }
end

I have this additionnal module (which this work great and isn't the actual problem):

module SubdomainHelper
def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    host = ActionMailer::Base.default_url_options[:host]
    [subdomain, host].join
end

def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
        options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
end
end

But when I get the json feed I have this error:

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

pointing to the "as_json" method of user model.

of course each environment implement default_url_options, in dev.rb:

config.action_mailer.default_url_options = {:host => 'my_app:3000'}

I don't understand why and how I fix it. Please help me.

Upvotes: 3

Views: 1603

Answers (2)

sj26
sj26

Reputation: 6833

To use the url helper root_path in your model I presume you are mixing in Rails.application.routes.url_helpers or similar. These helpers always construct URLs referencing default_url_options. ActionController figures out these default options from the current request. config.action_mailer.default_url_options is only for mailers which have no request to intuit defaults from, not for use in models. Views delegate to the controller/mailer. Each class that mixes these helpers in must provide default_url_options, but generally it's just a bad idea to redefine it. Supply the URL from the controller, mailer or view.

If you really must, in your model: delegate :default_url_options, to: ActionMailer::Base

Upvotes: 1

kidbrax
kidbrax

Reputation: 2434

I had a similar problem. Somehow it seemed to be related to actionpack's url_helper and my field name. Seems to be an issue with field names ending in *_url. Don't fully grok why but I had a field named login_url that I renamed to login_uri (notice the change from l to i) and it fixed my problem.

Upvotes: 1

Related Questions