Rails ActionController::Parameters
is a convenient way to pass data from a request to a controller action.
It allows us to choose which attributes should be permitted for mass updating and thus prevents accidentally exposing parameters that shouldn’t be exposed.
Before exclude?
To check if the given key is present in the parameters, we can use the include?
method, but ActionController::Parameters
does not provide any method to check if the given key is not present in the parameters.
params = ActionController::Parameters.new(name: "John", age: 26)
params.include?("name") #=> true
After exclude?
Rails 7.1 adds exclude? method to ActionController::Parameters. It is the inverse of include?
method.
The exclude?
method returns true
if the given key is not present in the parameters.
params.exclude?("name") #=> false
params.exclude?("admin") #=> true
Before extract_value
Rails ActionController::Parameters
did not provide a method for extracting parameter values for the given key separated by delimiter, so we had to do it manually.
params = ActionController::Parameters.new(tools: "git,vscode,jira")
# Extract tools parameter values into an array
params[:tools].split(",").map(&:strip)
#=> ["git", "vscode", "jira"]
After extract_value
Rails 7.1 adds extract_value method to ActionController::Parameters.
The extract_value
method returns parameter value for the given key separated by delimiter. It handles the splitting
and returns an array of values.
It takes below arguments
- key: The key of the parameter we want to extract.
- delimiter (optional): The character used to split the string
params = ActionController::Parameters.new(tools: "git,vscode,jira")
params.extract_value(:tools)
#=> ["git,vscode,jira"]
params.extract_value(:tools, delimiter: ",")
#=> ["git", "vscode", "jira"]
If the given key is not present, it returns nil
.
params.extract_value(:names)
#=> nil
If the given key‘s value contains blank elements, then the returned array will include empty strings.
params = ActionController::Parameters.new(tools: "git,vscode,,jira")
params.extract_value(:tools)
#=> ["git,vscode,,jira"]
params.extract_value(:tools, delimiter: ",")
#=> ["git", "vscode", "", "jira"]
Refer