Class: ActionController::Parameters
- Inherits:
-
Object
- Object
- ActionController::Parameters
- Defined in:
- lib/rails/pattern_matching.rb
Instance Method Summary collapse
-
#deconstruct_keys(keys) ⇒ Object
Returns a hash of parameters for the given keys.
Instance Method Details
#deconstruct_keys(keys) ⇒ Object
Returns a hash of parameters for the given keys. Provides the pattern matching interface for matching against hash patterns. For example:
class PostsController < ApplicationController
before_action :find_post
# PATCH /posts/:id
def update
case post_params
in { published: true, ** } if !can_publish?(current_user)
render :edit, alert: "You are not authorized to publish posts"
in permitted if @post.update(permitted)
redirect_to @post, notice: "Post was successfully updated"
else
render :edit
end
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body, :published)
end
end
Note that for security reasons, this method will only deconstruct keys that have been explicitly permitted. This is to avoid the potential accidental misuse of the ‘**` operator.
Note: as an optimization, Hash#deconstruct_keys (and therefore ActiveSupport::HashWithIndifferentAccess#deconstruct_keys) always returns itself. This works because the return value then has #[] called on it, so everything works out. This can yield some somewhat surprising (albeit correct) results if you call this method manually.
213 214 215 216 217 218 219 |
# File 'lib/rails/pattern_matching.rb', line 213 def deconstruct_keys(keys) if permitted? to_h.deconstruct_keys(keys) else raise ArgumentError, "Only permitted parameters can be deconstructed." end end |