2

How would I get all the values in the form input fields below by iterating through ans[n] where n = 1...3 in a controller?

<input type="text" name="ans[1]" value="Test 1">
<input type="text" name="ans[2]" value="Test 2">
<input type="text" name="ans[3]" value="Test 3">
1
  • (I guess) params[:ans] should be an array Commented Aug 19, 2013 at 16:41

2 Answers 2

3

You can loop on this params by doing this in your controller:

#controller
params[:ans].each do |value|
  puts value # should print the values for each input
end

If the params[:ans] is an array of hashes, you can access to its attributes like this:

params[:ans].each do |answer_attributes|
  puts answer_attributes['1']
end
Sign up to request clarification or add additional context in comments.

1 Comment

If params[:ans] is this array: { '1' => 'Test } , how do I access 'Test' ?
1

You can loop through the values of the param hash.

params[:ans].values.each do |value|
  puts value
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.