Reputation: 171341
Is there a way to require
an array when using strong parameters in Rails 4?
> params = ActionController::Parameters.new(contacts: [])
=> {"contacts"=>[]}
> params.require(:contacts)
ActionController::ParameterMissing: param not found: contacts
Upvotes: 2
Views: 4003
Reputation: 2259
As Steve Wilhelm noted, it works if the array is non-empty. It only fails on your example because the contacts array is empty. But that's usually the desired behavior.
If you don't care what's in the array, just use permit.
That said, I'd imagine the most common case is that you want an array of hashes with known keys. I would do that this way:
# Returns an array of contacts after checking the params shape
# Use instead of params[:contacts]
def contacts_params
params.permit(contacts: %i(id name phone address))
params.require(:contacts)
end
Upvotes: 4
Reputation: 6260
It appears you can have arrays of Scalars, This works
> params = ActionController::Parameters.new(contacts: [nil])
=> {"contacts"=>[nil]}
> params.require(:contacts)
=> [nil]
> params = ActionController::Parameters.new(contacts: [1])
=> {"contacts"=>[1]}
> params.require(:contacts)
=> [1]
Here is the description from documentation
The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.
To declare that the value in params must be an array of permitted scalar values map the key to an empty array:
params.permit(id: [])
Upvotes: 0