ruby-on-rails – 在rails中保存用户模型中的自定义字段4

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在rails中保存用户模型中的自定义字段4前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我做了一个设计用户模型,并添加了其他字段.当我创建和帐户一切正常,只有电子邮件,pw和pw conf.

然后我想允许用户去编辑页面并填写可选的附加字段.
但是,当他们提交时,一切都保存为零.

class RegistrationsController < Devise::RegistrationsController

   before_action :configure_permitted_parameters,if: :devise_controller?

   def configure_permitted_parameters
     devise_parameter_sanitizer.for(:sign_in){ |u| u.permit(:email,:password) }
     devise_parameter_sanitizer.for(:sign_up){ |u| u.permit(:name,:username,:about,:email,:password,:password_confirmation)}
     devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:name,:password_confirmation) }
   end

   def update
     self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
     if resource.update_with_password(user_params)
       if is_navigational_format?
         flash_key = update_needs_confirmation?(resource,prev_unconfirmed_email) ? :update_needs_confirmation : :updated
         set_flash_message :notice,flash_key
       end
       sign_in resource_name,resource,:bypass => true
       respond_with resource,:location => after_update_path_for(resource)
     else
       clean_up_passwords resource
       respond_with resource
     end
   end

   def user_params 
     params.require(:user).permit(:email,:current_password,:password_confirmation,:name,:about) 
   end
 end

我得到这个输出在控制台,

ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
 Processing by Devise::RegistrationsController#update as HTML
 Parameters: {"utf8"=>"✓","authenticity_token"=>"EG8FtCTBohuG2uwUvIqmY7KTsmYY1nMAXqTfc0Li+eQ=","user"=>{"email"=>"a@a.com","name"=>"Aaron","username"=>"","about"=>"","password"=>"[FILTERED]","password_confirmation"=>"[FILTERED]","current_password"=>"[FILTERED]"},"commit"=>"Update"}

User Load (2.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id",1]]
Unpermitted parameters: name,username,about

但是当我在控制台(使用User.last)登录时,数据库中没有保存任何内容.我被卡住了,看着,不知道是什么错了…

解决方法

在Rails4中,我们有很强的参数

将以下行添加到您的application_controller.rb

before_filter :configure_devise_params,if: :devise_controller?
  def configure_devise_params
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name,:last_name,:gender,:password_confirmation)
    end
  end
原文链接:https://www.f2er.com/ruby/272256.html

猜你在找的Ruby相关文章