【问题标题】:Strong parameters with Devise with :current_password attribute具有 :current_password 属性的设计的强参数
【发布时间】:2013-05-30 07:14:54
【问题描述】:

关于在 RegistrationController 中添加 :current_password 属性是否正确的问题?

include ActiveModel::ForbiddenAttributesProtection 的用户模型

# app/model/user.rb

class User < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection

从 Devise 的密码控制器继承的密码控制器

# app/controllers/users/passwords_controller.rb

class Users::PasswordsController < Devise::PasswordsController
  def resource_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
  private :resource_params
end

从 Devise 的注册控制器继承的注册控制器

# app/controllers/users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  def resource_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation, :current_password)
  end
  private :resource_params
end

Route for Devise 使用指定用户的密码和注册控制器。

# config/routes.rb

devise_for :users, :controllers => {:registrations => "users/registrations", :passwords => "users/passwords"}

RegistrationsController 中,我必须添加属性:current_password 以便用户能够编辑他们的个人资料。

我问的原因是没有strong_parameters 我只会为:email, :password, :password_confirmation, :remember_me 指定一个attr_accessible

非常感谢任何见解。

【问题讨论】:

  • 不确定这是否是最好的方法,您不想将其放在用户级别而不是注册级别吗?

标签: ruby-on-rails devise ruby-on-rails-3.2 strong-parameters


【解决方案1】:

我相信您的方法是正确的。至少看起来其他人也在使用它。

https://gist.github.com/kazpsp/3350730/#comment-833882 https://gist.github.com/bluemont/e304e65e7e15d77d3cb9

我怀疑你已经遇到过这个问题,但我想我会为了其他可能在未来发现这个问题的人而回答。

编辑:由于问题(和我的答案)专门针对在控制器级别与模型添加 :current_password 的适当性(不确定您甚至会如何做后者),所以我的答案的原始部分仍然站立。但是,似乎 Devise 的最新模块(至少从 3.0.0.rc 开始)已经消除了覆盖 resource_params 的能力,而是将该方法拆分为几个更具体的方法,如 sign_up_params、create_account_params 等以获得更好的效果粒度控制。虽然我确实让我的应用程序单独覆盖这些新方法,但似乎在 Devise README 中描述并引用 here 的“before_filter”(rails 4 中的before_action)方法是首选方式,并且可能更易于维护嗯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多