Include Rails.application.routes.url_helpers force the ArgumentError Missing host to reference

I am developing Rails 3.1.1.

Including url_helpers in Model raises an ArgumentError when saving the model.

class Medium < ActiveRecord::Base include Rails.application.routes.url_helpers . . end class MediaController < ApplicationController def create @medium = Medium.new(params[:medium]) @media.save # => cause ArgumentError end end 

ArgumentError (Missing host for reference! Provide parameter: host, set default_url_options [: host] or set: only_path to true):

Another model, which also includes url_helper, does not cause an error.
What's wrong? Thanks in advance.

+6
source share
2 answers

You need to pass the host as an argument in the call in which you use the helper:

Rails.application.routes.url_helpers.media_url(:host => "localhost:3000")

or another route like this:

Rails.application.routes.url_helpers.media_url(self, :host => AppConfig.host)

where AppConfig.host is the host depending on the environment (localhost: 300 for env development).

+3
source

This error usually occurs when we try to use any URL helper in places where it should not be used. For example, if I try to create a password entry URL from the action of the mailer class using reset_password_url(@user) , I get the same error.

Please make sure that you do not use any _path or _url methods in your model class. Moreover, I do not think this is the best practice for the url_helpers user inside the model.

-2
source

Source: https://habr.com/ru/post/900691/


All Articles