Display link in Rails form error message

后端 未结 6 2097
执笔经年
执笔经年 2021-02-05 18:47

On our sign-up form, we validates_uniqueness_of :email

When the a user is attempting to use our sign up form and they specify an existing email address, I\'

6条回答
  •  忘了有多久
    2021-02-05 19:09

    I know this is an old question, but for future users who want to insert a link into an error message, here are some guidelines that worked for me.

    First, the I18n error messages are assumed html safe already, so you can go ahead and write a suitable error message. In this example, I'm changing an "email is taken" message.

    # config/locales/en.yml
    activerecord:
      errors:
        models:
          user:
            attributes:
              email:
                taken: 'has already been taken. If this is your email address, try logging in instead.'
    

    Notice the interpolated variable %link.

    Now all you need to is pass in a value for that variable in your validator, like so:

    # app/models/user.rb
    validates :email, :uniqueness => {:link => Rails.application.routes.url_helpers.login_path}
    

    (By default, any options you pass in here will automatically be sent over to the I18n translator as variables, including some special pre-populated variables like %value, %model, etc.)

    That's it! You now have a link in your error message.

提交回复
热议问题