Tip: Return True for Model Hooks

Everyone loves before_create and before_save. Recently it came in very handy for logging hits to objects. If the user is logged in, I want to store the user's full name and the user's type, otherwise, keep those null. So I added this to my PostHit model:

 
def before_create
  if self.user
    self.user_name = self.user.full_name
    self.user_type = self.user.class.name
  end
end
 

I fired up my browser to find that the records weren't being created. I was calling them in the Post model via:

 
def log_hit(user = nil)
  self.hits << PostHit.create(:user => user)
end
 

Everything looked right, so what was wrong?

Before Hits Need to Return True

In my before_create hook, if user is nil, then the method returns nil, which is false, which prevents the instance from being created. Thus, return true.

 
def before_create
  if self.user
    self.user_name = self.user.full_name
    self.user_type = self.user.class.name
  end
  return true
end
 

Viola!

Post a Comment

Your email is never published nor shared. Required fields are marked *