devise-strong params

教程
1.简单参数增加方法:
在application/controller中加入(username 是你想加的参数)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
end
end
```
<!--more-->
2.如果你要增加的是nested attributes(与其他model有关联的参数?)[nested attributes](http://api.rubyonra ils.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html),也就是说用accepts_nested_attri butes_for 时,你就要告诉devise所有的关联和类型。devise才会同意你改掉devise的默认值或者进行一些用户操作。

(1)simple scalar values(简单标量值):eg
```ruby
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_in) do |user_params|
user_params.permit(:username, :email)
end
end

(2)array:eg

1
2
3
4
5
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit({ roles: [] }, :email, :password, :password_confirmation)
end
end

For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see

(3) 如果你有好几个 Devise models, 你想在每个model中设置不同的参数(parameter sanitizer)。 我们就需要从 Devise::ParameterSanitizer继承并且添加你自己的逻辑:

1
2
3
4
5
6
class User::ParameterSanitizer < Devise::ParameterSanitizer
def initialize(*)
super
permit(:sign_up, keys: [:username, :email])
end
end

然后让你的controller调用它:

1
2
3
4
5
6
7
8
9
10
11
class ApplicationController < ActionController::Base
protected

def devise_parameter_sanitizer
if resource_class == User
User::ParameterSanitizer.new(User, :user, params)
else
super # Use the default one
end
end
end