Did You Know? Validating belongs_to Relationships

This is one of those things that is probably obvious to some, and just not known to some. I was in that latter description up until a few minutes ago. It's that you can easily validate any belongs_to relationship by simply using valdiates_presence_of.

class Comment < ActiveRecord::Base
  belongs_to :article

  validates_presence_of :article

If you instantiate a new Comment, and don't assign an Article to the comment instance, the record won't save. I have to say, that seemed pretty obvious. But there is another interesting piece to this. Say I passed the article_id in the params and tried to assign that to our instance

comment =
comment.article_id = params[:article_id]

If article_id corresponds to a real article in our database, then comment.article will have be assigned an Article with that id. Now if params[:article_id] happens to be some id which doesn't exist, like 99999999999, then comment.article will be nil and thus the record fails validation. This means that you don't have to test for the existence of the Article against your records because rails will do this for you when it checks to see if comment.article is nil or not.


comments powered by Disqus