Custom validation message (in model file) that includes a path not working

365 views Asked by At

In the user model file I have included:

validates :email,  uniqueness: { case_sensitive: false, message: "You can reset your password " + link_to("here", new_password_reset_path) }

On loading the page on the development server, this generates the error:

undefined local variable or method `new_password_reset_path' for #<Class:0x007f4d36863460>

The alternative code below has the same result/error message.

validates :email,  uniqueness: { message: "You can reset your password #{link_to("here", new_password_reset_path)}" }

Is it not possible to refer to a path in the model file? If not, how could I implement the intended here?


Update: At first it seemed that the solutions that included Rails.application.routes.url_helpers in the model file worked. And indeed in development they worked. However, as it turned out, they don't work in production. They crash the site on Heroku. This post also seems to refer to something similar and seems to indicate that you should not use Rails.application.routes.url_helpers in a model file. After pushing to Heroku, when I try to open the website it says "Application Error". So I checked the heroku logs and found:

app[web.1]: [3] ! Unable to load application: NoMethodError: undefined method `new_password_reset_path' for #<Module:0x007f7392350b08>
app[web.1]: /app/app/models/user.rb:32:in `<class:User>': undefined method `new_password_reset_path' for #<Module:0x007f7392350b08> (NoMethodError)

Does anyone have an alternative solution that also works on Heroku / in production? That is, a solution how to include an url/path in a custom validation message in the model file.

1

There are 1 answers

11
Amit Sharma On BEST ANSWER

You can try this. I hope this will help.

config/locales/en.yml

en:
  activerecord:
    errors:
      messages:
        email: 'You can reset your password <a href="%{link}">here</a>.'

In User Model.

validates :email,  uniqueness: { case_sensitive: false, message: I18n.t("activerecord.errors.messages.email", link: Rails.application.routes.url_helpers.new_password_reset_url) }