簡體   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