TDH
TDH

Reputation: 567

Extracting IDs from params

I wonder if anyone could help with this. I am dynamically building a form with numbered text fields like:

<input name='product_quantity_<%= product.id %>' />

This produces params like: product_quantity_1, product_quantity_4, etc. I was thinking that I could access these parameters like param[:product_quantity_#{product.id}] but this doesn't work. How can I get the parameters dynamically? I hope I've asked this in the right way.

Thanks in advance,

Tom

Upvotes: 1

Views: 134

Answers (2)

Leonid Shevtsov
Leonid Shevtsov

Reputation: 14179

Соuldn't you use names like "product_quantity[#{id}]"? They will automatically become an array in Rails.

Upvotes: 1

rogeriopvl
rogeriopvl

Reputation: 54056

You can use the split function to get the id, although it's not an elegant solution:

ids = {}

for k in param.keys
  ids[k.split('_').last] => param[k]
end

This will give you a hash "ids" with all the id's and respective values.

Upvotes: 1

Related Questions