Skip to content

Instantly share code, notes, and snippets.

@basiszwo
Created May 13, 2011 10:27
Show Gist options
  • Save basiszwo/970312 to your computer and use it in GitHub Desktop.
Save basiszwo/970312 to your computer and use it in GitHub Desktop.
Missing default_host_options in rails model
# application_controller.rb
before_filter :default_hosts
# set dynamically to always correct paths and urls (dev, stage, testing)
def default_hosts
ActionController::Base.default_url_options[:host] = request.host_with_port
ActionMailer::Base.default_url_options[:host] = request.host_with_port
end
# my_model.rb
class MyModel < AR::Base
def return_url
Rails.application.routes.url_helpers.verify_paypal_payment_notifications_url(order_id)
end
end
# this results in
# Missing host to link to! Please provide :host parameter or set default_url_options[:host]
# so what's the best practise to get this error down?
@albertoperdomo
Copy link

I think it is general consense that you shouldn't be handling URLs in your models. If you really need to do this for an exceptional reason you can do it like this:

    include Rails.application.routes.url_helpers
    default_url_options[:host] = 'xxx' # usually read from config

Then you can use the helpers as usual:

    url = content_url(self)

@basiszwo
Copy link
Author

Thanks! I take this for now. Maybe there's an even nicer solution to this ...

@albertoperdomo
Copy link

I think if you are calling a method the preferred solution is to pass to the URL from the view, e.g.

    # app/models/foo.rb
    def some_fancy_method(url)
      # do something with url and return result
    end

    # app/views/foo.erb.html
    @foo.some_fancy_method(content_url(foo.content))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment