如何在Rails 4中为设计注册添加自定义字段? [英] How do i add a custom field to a devise registration in Rails 4?
问题描述
我正在尝试添加一个字段到我的注册页面使用devise。我遵循Devise文档中的说明。新领域是角色领域。我已经成功地将其迁移到数据库。我现在正试图让它的注册工作。这是新的应用程序控制器:
I am trying to add one field to my registration page that uses devise. I followed the instructions in the Devise document. The new field is the "role" field. I have already succesfully migrated it to the database. I am now trying to make it so that the signup works. Here is the new 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
这里是更改的用户模型:
And here is the changed User model:
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
一旦我添加了这两个文件,服务器甚至无法加载。如何成功添加角色字段?
Once I added these two files, the server cannot even load. How do I successfully add the role field?
编辑
这是我的routes.rb文件
Here is my routes.rb file
devise_for :users
root 'static_pages#home'
get 'student' => 'static_pages#index'
推荐答案
您还可以使用以下方法在设计用户表中添加自定义字段。
You can also use following approach to add custom field in devise user table.
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
这篇关于如何在Rails 4中为设计注册添加自定义字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!