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
.
1class Comment < ActiveRecord::Base
2 belongs_to :article
3
4 validates_presence_of :article
5end
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
1comment = Comment.new
2comment.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
comments powered by Disqus