This is more of a DB question…but say I have a model that has a
field that I want to populate with specific items, see below for an
example. What is the best way to do this in Rails?
Model:
name, type, date - where “type” must be one of “male”, “female”.
Do I do this in the DB through constraints, or in the Rails app?
You can to the male/female checking in your model. Add this at the top:
validates_inclusion_of :type, :in => %w( male female ), :message =>
“woah!
what are you then!??!!”
But what if someone connects to the DB from outside of the Rails app
and populates the DB from another source? There is no constraint on
the table, right?
Correct, the db would not have the constraint on it. In that case you
probably want a constraint at both the db and model level. The nice
thing
about using the model level constraint is it uses Rails validation and
will
give a more user friendly error message than having to deal with a db
level
constraint violation, and present that error to the user.