繁体   English   中英

如何在Rails 4中为设计注册添加自定义字段?

[英]How do i add a custom field to a devise registration in Rails 4?

我正在尝试在使用devise的注册页面中添加一个字段。 我遵循了Devise文档中的说明。 新字段是“角色”字段。 我已经成功地将其迁移到数据库。 我现在正在尝试使注册生效。 这是新的applicationcontroller:

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

    def devise_parameter_sanitizer
        if resource_class == User
          User::ParameterSanitizer.new(User, :user, params)
        else
          super # Use the default one
        end
    end
end

这是更改后的用户模型:

class User::ParameterSanitizer < Devise::ParameterSanitizer
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def sign_up
    default_params.permit(:email, :role)
  end
end 

一旦添加了这两个文件,服务器甚至无法加载。 如何成功添加角色字段?

编辑

这是我的routes.rb文件

devise_for :users
root 'static_pages#home'
get 'student' => 'static_pages#index'

您也可以使用以下方法在设计用户表中添加自定义字段。

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
   devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:firstname, :lastname, :email, :password, :password_confirmation) } # The :firstname and :lastname are my custom fields.
  end

  protect_from_forgery with: :exception
end 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM