0

As a paranoid entry-level developer I was wondering if it is possible for a user to use some kind of query to insert data into a database through a form with a select field.

More specifically lets say in my db I have a Gender column (data type text) and in my form I am using the select tag and passing in 2 options Male and Female. Although in the html the user only has 2 options to select from but the db doesn't know that. The gender column will pretty much accept anything. I just wanted to know if a nuisance user can disregard the select options and somehow insert a silly answer into the Gender column? If so, how can I protect from that.

1

1 Answer 1

2

The thing you are talking about here is the validations need to be done before entering data to the database. Invalid data can come from anywhere ( directly from controller or from GUI) and its the responsibility of the model to validate the data before it commits to the database.

Go through these links.

http://api.rubyonrails.org/classes/ActiveRecord/Validations.html http://guides.rubyonrails.org/active_record_validations_callbacks.html

Sign up to request clarification or add additional context in comments.

4 Comments

Right. Its easy to validate presence or format or length and I have implemented that. How would I validate an option from a select field? In the case of Gender, maybe I can put insert a validation that the string == "Male" || "Female" or something along those lines. But lets say if there is a City option it would be kind of impractical for me to list out all the cities. Is there a better way to do that?
Good one. Those kind of validations has to be done on the controller side. For example, the controller knows the list of data that it has sent to the list box, when the data is coming from the GUI, it should do the sanity check with the list that it had used to populate along with the value returned from the GUI. That will ensure the user input is always valid.
Okay, that makes sense. What do you think about this approach. Using the"Validates Inclusion" method on the Model side. Would that be applicable. stackoverflow.com/questions/8582967/…
Yes. Provided your set is small enough like your gender example. If your parent set is big ( for example cities ) you cannot include everything in VALID_STATES, rather have to use a instance variable which keeps track of cities that you used to load the list box in first place.

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.