mirror of
https://github.com/varvet/pundit.git
synced 2022-11-09 12:30:11 -05:00
Merge pull request #502 from pablocrivella/refactor-permitted-attributes-method
Refactor permitted attributes method
This commit is contained in:
commit
bceb153256
2 changed files with 31 additions and 2 deletions
22
README.md
22
README.md
|
@ -669,6 +669,28 @@ end
|
|||
|
||||
If you have defined an action-specific method on your policy for the current action, the `permitted_attributes` helper will call it instead of calling `permitted_attributes` on your controller.
|
||||
|
||||
If you need to fetch parameters based on namespaces different from the suggested one, override the below method and return an instance of `ActionController::Parameters`.
|
||||
|
||||
```ruby
|
||||
def pundit_params_for(record)
|
||||
params.require(PolicyFinder.new(record).param_key)
|
||||
end
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```ruby
|
||||
# If you don't want to use require
|
||||
def pundit_params_for(record)
|
||||
params.fetch(PolicyFinder.new(record).param_key, {})
|
||||
end
|
||||
|
||||
# If you are using something like the jsonapi spec
|
||||
def pundit_params_for(_record)
|
||||
params.fetch(:data, {}).fetch(:attributes, {})
|
||||
end
|
||||
```
|
||||
|
||||
## RSpec
|
||||
|
||||
### Policy Specs
|
||||
|
|
|
@ -233,14 +233,21 @@ protected
|
|||
# If omitted then this defaults to the Rails controller action name.
|
||||
# @return [Hash{String => Object}] the permitted attributes
|
||||
def permitted_attributes(record, action = params[:action])
|
||||
param_key = PolicyFinder.new(record).param_key
|
||||
policy = policy(record)
|
||||
method_name = if policy.respond_to?("permitted_attributes_for_#{action}")
|
||||
"permitted_attributes_for_#{action}"
|
||||
else
|
||||
"permitted_attributes"
|
||||
end
|
||||
params.require(param_key).permit(*policy.public_send(method_name))
|
||||
pundit_params_for(record).permit(*policy.public_send(method_name))
|
||||
end
|
||||
|
||||
# Retrieves the params for the given record.
|
||||
#
|
||||
# @param record [Object] the object we're retrieving params for
|
||||
# @return [ActionController::Parameters] the params
|
||||
def pundit_params_for(record)
|
||||
params.require(PolicyFinder.new(record).param_key)
|
||||
end
|
||||
|
||||
# Cache of policies. You should not rely on this method.
|
||||
|
|
Loading…
Add table
Reference in a new issue