包含无效路径的自定义验证消息(在模型文件中)
Custom validation message (in model file) that includes a path not working
在我包含的用户模型文件中:
validates :email, uniqueness: { case_sensitive: false, message: "You can reset your password " + link_to("here", new_password_reset_path) }
在开发服务器上加载页面时,会生成错误:
undefined local variable or method `new_password_reset_path' for #<Class:0x007f4d36863460>
下面的替代代码具有相同的 result/error 信息。
validates :email, uniqueness: { message: "You can reset your password #{link_to("here", new_password_reset_path)}" }
是不是不能引用模型文件中的路径?如果没有,我怎么能在这里实现预期的目标?
更新: 起初似乎模型文件中包含 Rails.application.routes.url_helpers
的解决方案有效。事实上,他们在发展中发挥了作用。然而,事实证明,它们在生产中不起作用。他们在 Heroku 上使网站崩溃。 post 似乎也指类似的东西,似乎表明您不应在模型文件中使用 Rails.application.routes.url_helpers
。推送到 Heroku 后,当我尝试打开该网站时,它显示 "Application Error"。所以我检查了 heroku 日志并发现:
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)
有没有人有在 Heroku 上/在生产中也适用的替代解决方案? 即如何在模型文件的自定义验证消息中包含[=36=]的解决方案。
你可以试试这个。我希望这会有所帮助。
config/locales/en.yml
en:
activerecord:
errors:
messages:
email: 'You can reset your password <a href="%{link}">here</a>.'
在用户模型中。
validates :email, uniqueness: { case_sensitive: false, message: I18n.t("activerecord.errors.messages.email", link: Rails.application.routes.url_helpers.new_password_reset_url) }
在我包含的用户模型文件中:
validates :email, uniqueness: { case_sensitive: false, message: "You can reset your password " + link_to("here", new_password_reset_path) }
在开发服务器上加载页面时,会生成错误:
undefined local variable or method `new_password_reset_path' for #<Class:0x007f4d36863460>
下面的替代代码具有相同的 result/error 信息。
validates :email, uniqueness: { message: "You can reset your password #{link_to("here", new_password_reset_path)}" }
是不是不能引用模型文件中的路径?如果没有,我怎么能在这里实现预期的目标?
更新: 起初似乎模型文件中包含 Rails.application.routes.url_helpers
的解决方案有效。事实上,他们在发展中发挥了作用。然而,事实证明,它们在生产中不起作用。他们在 Heroku 上使网站崩溃。 Rails.application.routes.url_helpers
。推送到 Heroku 后,当我尝试打开该网站时,它显示 "Application Error"。所以我检查了 heroku 日志并发现:
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)
有没有人有在 Heroku 上/在生产中也适用的替代解决方案? 即如何在模型文件的自定义验证消息中包含[=36=]的解决方案。
你可以试试这个。我希望这会有所帮助。
config/locales/en.yml
en:
activerecord:
errors:
messages:
email: 'You can reset your password <a href="%{link}">here</a>.'
在用户模型中。
validates :email, uniqueness: { case_sensitive: false, message: I18n.t("activerecord.errors.messages.email", link: Rails.application.routes.url_helpers.new_password_reset_url) }