Ben
Ben

Reputation: 25807

How parse checkbox values in server side(rails)?

I am beginner in ruby + rails.

I have problem to get values in controler of checkbox with params[] of rails.

The Case:

I have simple form that that have checkbox and i want to sent reqular request to controller action with user checked values. The problem that params[:rating] can have few values.

My case: html user side:

<form id="ratings-form">
     <input name="rating" type="checkbox" value="G">G
     <input name="rating" type="checkbox" value="PG">PG
     <input name="rating" type="checkbox" value="PG-13">PG-13
     <input name="rating" type="checkbox" value="R">R
     <input type="submit" value="refresh">
</form>

controller action code to parse checked values: (get error 1. params[:rating] == nil or params[:rating] == string)

params[:rating].each  do |rat|
     p rat;
end

What should i change in the code to make it work?

Thanks

Upvotes: 1

Views: 1891

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230326

Try this HTML

<input name="rating[]" type="checkbox" value="G">G
<input name="rating[]" type="checkbox" value="PG">PG
<input name="rating[]" type="checkbox" value="PG-13">PG-13
<input name="rating[]" type="checkbox" value="R">R

Then you should have an array in params[:rating].

Upvotes: 4

Related Questions