Fenster
Fenster

Reputation: 3

Rails access form parameter that is an array

I have a form that allows for the entry of multiple ids like:

<input name="the_ids[]"  type="text" placeholder="Enter an ID" />
<input name="the_ids[]"  type="text" placeholder="Enter an ID" />
<input name="the_ids[]"  type="text" placeholder="Enter an ID" />

When the form submits I get the params being passed as:

"the_ids"=>["1, 2, 3"],

In the controller I am trying to access them as:

params[:the_ids[]].each do |id|
  do_something_with(id)
end

I keep getting the error:

wrong number of arguments (0 for 1..2)
> params[:the_ids[]].each do |id|

The trace shows the following:

app/controllers/the_controller.rb:10:in `[]'  

I cannot figure this out. I've reviewed some other posts and tried to access in alternative syntax like:

params["the_ids[]"]

But that produced an error stating that is was a nil class...

Please advise if more details are needed.

Upvotes: 0

Views: 75

Answers (1)

libcthorne
libcthorne

Reputation: 417

As you can see in "the_ids"=>["1, 2, 3"], the parameter name is the_ids and you can access it using params[:the_ids].

params[:the_ids].each do |id|
  do_something_with(id)
end

The use of the_ids[] in name="the_ids[]" is only needed on the client-side to tell Rails that the_ids is to be read as an array parameter.

Upvotes: 2

Related Questions