Display link in Rails form error message

后端 未结 6 2034
执笔经年
执笔经年 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 18:48

    This may not streamline well with the translations, but here's a suggestion:

    In your user_controller#create action, wrap everything you already have with an if statement. Here's a rough example:

    class UserController < ApplicationController
    ...
    
    def create
      if User.find(params[:email])
        flash[:alert] = "This email address is in use.  You can ".concat(generate_reset_password_link(params[:email])
        render :action => 'new'
      else
        <your current code>
      end
    end
    

    After this, you'll have to write a helper method generate_reset_password_link, but I think this mostly respects the MVC layout. The controller is meant to interface with the view and model. It is violating the DRY principle a little, since you're essentially bypassing validates_uniqueness_of :email, but you get some custom behavior. DRY doesn't seem to be 100% achievable to me if you want to make more complex apps, but perhaps you can refine this and prove me wrong ;)

    You may have to massage this a little so that the render :action => 'new' will repopulate itself with the previously entered data (in case the user just mistyped his own email address and it actually isn't in the system).

    If you decide to use this approach, I would throw a comment in both the controller and the model indicating that the email uniqueness is essentially checked in 2 places. In the event someone else has to look at this code, it'll help them to understand and maintain it.

    0 讨论(0)
  • 2021-02-05 18:52

    After hours trying to figure this out for Rails 4 with devise, I realised you can just add the link directly into the validation:

    # app/models/user.rb
    validates :username, presence: true, uniqueness: {:message => "username has already been taken - <a href='/users'>search users</a>" }
    

    where the link in this case is my users index. Hopefully this will help someone!

    0 讨论(0)
  • 2021-02-05 18:57

    Stumbled across this today:

    http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

    If you need to access this auto-generated method from other places (such as a model), then you can do that by including ActionController::UrlFor in your class:


    Step 1

    Getting awareness of named routes to the model is the hard part; this gets me most of the way.

    Now I can do something along the lines of

    class User < ActiveRecord::Base
      include Rails.application.routes.url_helpers
    
      def reset_password_uri
        new_user_password_path(self)
      end
    end
    
    # User.find(1).reset_password_uri => "/users/password/new"
    

    Step 2

    So we have access to the named route, but now we need to inject it into the YAML message.

    Here's what I just learned about YAML variables:

    # en.yml
    en:
      welcome: "Hello, %{username}!"
    
    # es.yml
    es:
      welcome: "¡Hola, %{username}!"
    

    I can inject the username by including a hash with the t method

    <div id="welcome">
      <%= t :welcome, :username => @user.username %>
    </div>
    

    Step 3

    Now we just need a way to add interpolation to the error message described in the original question. This is where I am currently stuck :(

    0 讨论(0)
  • 2021-02-05 19:00

    If you're using 2.3.x, replace your call to error_messages with your own helper, written in UsersHelper. It should accept the FormBuilder or an ActiveRecord object and adjust the error message as you see fit. You could make as many customizations as you like, or it could be as simple as a gsub:

    def user_error_messages(f)
      find_error = "This email address is already in use."
      replacement = "This email address is already in use. #{link_to(...)} to reset your password"
      f.error_messages.sub(find_error, replacement).html_safe
    end
    

    If you're using Rails3, make a helper method to simply process @user.errors.full_messages before they're emitted to the view.

    0 讨论(0)
  • 2021-02-05 19:04

    You can place a tag of your own like ~[new_password_url] in your error messages. Then at the point of rendering your error messages gsub ur tag with the actual. if you want to do it generically you can get the path out using regexp and then eval it to get the url then gsub it back in. make you use the raw method if you are putting html into your text.

    0 讨论(0)
  • 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 <a href="%{link}">logging in</a> 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.

    0 讨论(0)
提交回复
热议问题