Display link in Rails form error message

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

    <%= t :welcome, :username => @user.username %>

    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 :(

提交回复
热议问题