添加自定义字段/列使用Rails制定4

添加自定义字段/列使用Rails制定4

问题描述:

我试图(通过devise GEM)和一个full_name场/列添加到我的用户模型的Rails 4添加自定义字段/列使用Rails制定4

大多数例子在线recommend using attr_accessible,但听起来这应该在Rails 4中以不同方式接近。

如何将full_name添加到我的用户模型?我已经能够成功运行迁移。

文件:迁移> add_full_name_to_users

class AddFullNameToUsers < ActiveRecord::Migration 
    def change 
    add_column :users, :full_name, :string 
    end 
end 

文件:注册>应用程序/视图/设计/注册/ 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 %> 
. 
. 
. 
+0

此相关是:以http://*.com/questions/164714​​98/adding-extra-registration场设计? – 2013-05-26 17:40:44

+0

@dimitrismistriotis是的,看起来像一样的问题。 – 2013-06-06 00:52:01

一旦你的模式有其FULL_NAME属性,你将必须配置为#sign_up和#允许参数account_update制定行动。

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 
+0

完美适合我。谢谢! – Sparkmasterflex 2014-05-01 14:22:10

+2

真的很棒!必须包含在设计文档中! – DoctorRu 2014-07-22 13:26:03

启用设计,而不是attr_accessible强参数。要做到这一点,创建一个新的initiliazer与内容:

DeviseController.class_eval do 
    def resource_params 
    unless params[resource_name].blank? 
     params.require(resource_name).permit(:email, :password, :password_confirmation, :remember_me) 
    end 
    end 
end 

从色器件文档:

当您自定义你自己的看法,你可能会增加新的属性形式。 Rails 4将参数清理从模型转移到控制器,导致Devise在控制器中处理这个问题。

您应检查以下链接找到最能满足您的需求的办法: https://github.com/plataformatec/devise#strong-parameters

+0

加一个包含文档链接 – Sam 2014-11-25 12:31:17

这个解决方案应该工作,与sign_up更新工作:

class ApplicationController < ActionController::Base 
    before_filter :configure_permitted_parameters, if: :devise_controller? 

    protected 

    def configure_permitted_parameters 
     devise_parameter_sanitizer.permit(:sign_up,  keys: [:full_name]) 
     devise_parameter_sanitizer.permit(:account_update, keys: [:full_name]) 
    end 
    end 
+1

我得到错误'未定义的方法' – Sidhannowe 2014-02-10 14:48:43