Best way to do model validation and pass errors?


Hi all,

Following up on the best practices series, what is the best way to do
some more advanced model validation, beyond presence, numericality, etc.
For example, I want to do some checks on the database to see if a user
has performed a certain action before (such as joining a group), and
then pass the appropriate error messages back to the controller?

Having followed the best practices to move as much logic out of the
controller and into the model, I have created a function
Group.add_user(user) that checks for existing membership in the group,
and then makes the association. However, I’d like to be able to pass an
error message back into the flash notice if the user has already joined
the group. I can think of two ways of doing this…

In controller:
if group.check_ownership(user)
flash[:notice] = “error message”

I don’t like this method, because it seems to be putting logic back into
the controller; this logic could get more complex outside of this simple

In Group model:
def add_user
if !group.check_ownership(user)
return “error message” # or return an error number

Write a validator? A brief read in DHH’s book seems to suggest
validators are more for checking database content than for things like
checking associations.

Is there a better method? Any help much appreciated!