Display link in Rails form error message

后端 未结 6 2036
执笔经年
执笔经年 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
        
      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.

提交回复
热议问题