Forum: Ruby on Rails Best way to do model validation and pass errors?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
F0befb20d021fc1f6ce30df5a12d36a3?d=identicon&s=25 Jay Bo (booyau)
on 2009-03-01 00:15
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!
This topic is locked and can not be replied to.