设计配置

Devise configuration

我目前想用设计登录。在电子邮件和密码之上,我想要一个用户名。我生成了迁移:

class AddUsernameToBuyer < ActiveRecord::Migration
  def change
    add_column :buyers, :username, :string
    add_index :buyers, :username, unique: true
  end
end

我还在注册视图中添加了用户名:

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
   <%= f.label :username %> <br />
   <%= f.text_field :username %>
  </div>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @validatable %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

然后我将应用程序控制器用户名作为允许参数输入:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username) }
    end

    def after_sign_up_path_for(resource)
      redirect_to root_path
    end
end

当我尝试注册时,我被重定向到:http://localhost:3000/buyers/sign_up

填写详细信息后,我点击注册,我希望自己被重定向到 root_page。然而,devise 将我重定向到 http://localhost:3000/buyers,它告诉我,即使我添加了它,我也不能有一个空白的用户名。

我怎样才能改变这个behavior/fix呢?

您需要在 after_sign_in_path_for(resource) 中生成 url。试试下面的代码。

def after_sign_in_path_for(resource)
  root_path
end

要重定向,您需要将 after_sign_up_path_for 放入 RegistrationsController。首先创建它以覆盖 Devise 的本机控制器。

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    root_path
  end
end