Multiple types for an attribute with params.expect

Previously I’ve been using this to say that I expect value to be either a scalar, an array of values, or a hash:

def submission_params
  params.require(:submission).permit(
    results_attributes: [ :element_id, :value, { value: [] }, { value: {} } ]
  )
end

It’s a form builder and for legacy reasons the value can be any of those types since it could be a simple text field, or at its most complicated, a date field for example.

I can’t seem to find a way to make this work with params.expect. Just wondering if anyone else has found a way?

1 Like

I had no problem reproducing your desired behavior with params.expect.

p = ActionController::Parameters.new({ submission: { results_attributes: [{ value: 1 }, { value: [1, 2] }, { value: { a: 1, b: 2 } }] } })
p.expect(submission: { results_attributes: [[:value, { value: [] }, { value: {} }]] })
=> #<ActionController::Parameters {"results_attributes" => [#<ActionController::Parameters {"value" => 1} permitted: true>, #<ActionController::Parameters {"value" => [1, 2]} permitted: true>, #<ActionController::Parameters {"value" => #<ActionController::Parameters {"a" => 1, "b" => 2} permitted: true>} permitted: true>]} permitted: true>

Maybe your solution is missing the double array brackets around the value of `results_attributes`?

That’s so interesting! I’ll give it a go. I’m sure it’ll work.