Validate check box data in rails
Posted by Jesse Rodgers on October 06, 2008 at 10:32 PM
A friend is working on a rails app for me that will run the voting for the UW Staff Association. We had some simple requirements and she threw together the app pretty quickly. The poll requires options like ‘select one of three’ or ‘select three of five’ so there had to be check boxes that have id values… look something like:
input id="option[ids][]" name="option[ids][]" value="36" type="checkbox"
In the case of ‘select three of five,’ if you accept the value of the input you need to check someone didn’t just change the value of all the boxes to the same so they don’t vote three times for one thing. This was her quick fix:
unless params[:option][:ids].uniq.size == params[:option][:ids].size
flash.now[:error] = "You can't vote for the same thing multiple times in one poll?"
return
end
The check just makes sure the same id’s aren’t submitted twice. Being a total rails novice I expected rails would have some pretty way to do this. The above is good (it works) but I had expected a more elegant data validation… I must expect too much.