添加自定义字段/列以使用 Rails 4 进行设计 [英] Add Custom Field/Column to Devise with Rails 4
问题描述
我正在尝试将 full_name
字段/列添加到我的用户模型(使用 devise
gem)和 Rails 4.
大多数在线示例推荐使用 attr_accessible,但听起来在 Rails 4 中应该采用不同的方法.
我如何将 full_name
添加到我的用户模型中?我已经能够成功运行迁移.
文件:迁移 > add_full_name_to_users
class AddFullNameToUsers <ActiveRecord::迁移定义改变add_column :users, :full_name, :string结尾结尾
文件:注册 > app/views/devise/registration/new.html
<预><代码>...<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|%><%= devise_error_messages!%><%= f.label :full_name %><%= f.text_field :full_name, :autofocus =>真%><%= f.label :email %><%= f.email_field :email %>...一旦您的模型具有其 full_name 属性,您就必须为 #sign_up 和 #account_update Devise 操作配置允许的参数.
class ApplicationController <动作控制器::基础before_action :configure_devise_permitted_parameters, if: :devise_controller?受保护def configure_devise_permitted_parametersregistration_params = [:full_name, :email, :password, :password_confirmation]if params[:action] == '更新'devise_parameter_sanitizer.for(:account_update) 做|你|u.permit(registration_params <<:current_password)结尾elsif params[:action] == '创建'devise_parameter_sanitizer.for(:sign_up) 做|你|u.permit(registration_params)结尾结尾结尾结尾
I'm attempting to add a full_name
field/column to my User model (using the devise
gem) and Rails 4.
Most of the examples online recommend using attr_accessible, but it sounds like this should be approached differently in Rails 4.
How would I add full_name
to my User model? I've been able to successfully run the migration.
File: Migration > add_full_name_to_users
class AddFullNameToUsers < ActiveRecord::Migration
def change
add_column :users, :full_name, :string
end
end
File: Registration > app/views/devise/registration/new.html
.
.
.
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= f.label :full_name %>
<%= f.text_field :full_name, :autofocus => true %>
<%= f.label :email %>
<%= f.email_field :email %>
.
.
.
Once your model has its full_name attribute, you will have to configure permitted parameters for the #sign_up and #account_update Devise actions.
class ApplicationController < ActionController::Base
before_action :configure_devise_permitted_parameters, if: :devise_controller?
protected
def configure_devise_permitted_parameters
registration_params = [:full_name, :email, :password, :password_confirmation]
if params[:action] == 'update'
devise_parameter_sanitizer.for(:account_update) do
|u| u.permit(registration_params << :current_password)
end
elsif params[:action] == 'create'
devise_parameter_sanitizer.for(:sign_up) do
|u| u.permit(registration_params)
end
end
end
end
这篇关于添加自定义字段/列以使用 Rails 4 进行设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!