instance method
require
Ruby on Rails 8.0.4
Since v4.0.13Signature
require(key)
This method accepts both a single key and an array of keys.
When passed a single key, if it exists and its associated value is either present or the singleton false, returns said value:
ActionController::Parameters.new(person: { name: "Francesco" }).require(:person) # => #<ActionController::Parameters {"name"=>"Francesco"} permitted: false>
Otherwise raises ActionController::ParameterMissing:
ActionController::Parameters.new.require(:person) # ActionController::ParameterMissing: param is missing or the value is empty or invalid: person ActionController::Parameters.new(person: nil).require(:person) # ActionController::ParameterMissing: param is missing or the value is empty or invalid: person ActionController::Parameters.new(person: "\t").require(:person) # ActionController::ParameterMissing: param is missing or the value is empty or invalid: person ActionController::Parameters.new(person: {}).require(:person) # ActionController::ParameterMissing: param is missing or the value is empty or invalid: person
When given an array of keys, the method tries to require each one of them in order. If it succeeds, an array with the respective return values is returned:
params = ActionController::Parameters.new(user: { ... }, profile: { ... })
user_params, profile_params = params.require([:user, :profile])
Otherwise, the method re-raises the first exception found:
params = ActionController::Parameters.new(user: {}, profile: {}) user_params, profile_params = params.require([:user, :profile]) # ActionController::ParameterMissing: param is missing or the value is empty or invalid: user
This method is not recommended for fetching terminal values because it does not permit the values. For example, this can cause problems:
# CAREFUL params = ActionController::Parameters.new(person: { name: "Finn" }) name = params.require(:person).require(:name) # CAREFUL
It is recommended to use expect instead:
def person_params params.expect(person: :name).require(:name) end
Parameters
-
keyreq
Source
# File actionpack/lib/action_controller/metal/strong_parameters.rb, line 519
def require(key)
return key.map { |k| require(k) } if key.is_a?(Array)
value = self[key]
if value.present? || value == false
value
else
raise ParameterMissing.new(key, @parameters.keys)
end
end
Defined in actionpack/lib/action_controller/metal/strong_parameters.rb line 519
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionController::Parameters