【问题标题】:Customizing Devise with Strong Parameters使用强参数定制设计
【发布时间】:2013-08-17 09:35:52
【问题描述】:

我正在使用 Rails 4.0.0 和 Devise 3.0.2,并尝试在 Devise README 中使用 this instruction 之后的强参数配置 Devise。

我在application_controller.rb写了这样的代码

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :nick
  end
end

然后我访问了http://localhost:3000/users/sign_up。我收到了NoMethodError in Devise::RegistrationsController#new,上面写着:

未定义的方法&lt;&lt;' for {}:ActionController::Parameters

并指向我写devise_parameter_sanitizer.for(:sign_up) &lt;&lt; :nick的确切行

我做错了什么吗?感谢您的帮助。

【问题讨论】:

  • 我尝试了完全相同的代码并得到相同的错误。 devise_parameter_sanitizer.for(:sign_up) 返回一个空的散列,因此无法在其上调用 &lt;&lt; 方法。我已经提交了[an issue][1],你可以关注它。 [1]:github.com/plataformatec/devise/issues/2574
  • @RafałCieślak 感谢您的确认,我会关注这个问题。

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


【解决方案1】:

试试:

    class ApplicationController < ActionController::Base
      ...
      before_filter :configure_permitted_parameters, if: :devise_controller?   
      ...
      def configure_permitted_parameters
         devise_parameter_sanitizer.for(:sign_up) { |u| 
            u.permit(:email, :password, :password_confirmation, :nick) 
         }
      end

它对我有用! :D

【讨论】:

  • 这个在模型中吗?
  • 我把 ApplicationController: before_filter :configure_permitted_pa​​rameters, if: :devise_controller?
【解决方案2】:

作为Jose Valim said,它是Devise 3.1.0.rc 的特性,这就是它不起作用的原因。您必须使用 README 中的其他语法。

【讨论】:

    【解决方案3】:

    一个问题与您的问题完全匹配:#2574 : devise_parameter_sanitizer.for(:sign_up) << :something raises an error

    事实上,像这样为强参数添加自定义字段的方法是 Devise 3.1 的新功能。

    由于 Rubygems.org 中的当前版本是 3.0.3,因此您暂时不能在您的 rails 项目中使用此方法。您必须像这样覆盖默认值:

    devise_parameter_sanitizer.for(:sign_up) do |u|
        u.permit :email, :password, :password_confirmation, :first_name, :last_name
    end
    


    但如果你真的需要,你可以编辑你的 Gemfile 并替换这一行

    gem 'devise', '3.0.3'
    

    有了这个:

    gem 'devise', github: 'plataformatec/devise', branch: 'master'
    

    然后您可以像这样轻松添加自定义字段:

    # Single field
    devise_parameter_sanitizer.for(:account_update) << :first_name
    # Multiple fields at a time
    devise_parameter_sanitizer.for(:account_update) << [:first_name, :last_name]
    

    但是请注意,目前这是一个候选版本3.1.0 RC1

    【讨论】:

    • 它总是一些小细节......如果他们在自述文件中为像我这样的可怜的 github 菜鸟提到这一点会很好...... FWIW 唯一有效的东西(在网络上尝试了几个不同的例子) 将我的 attrs 放入 u.permit 组中,就像 Carlos 上面提到的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多