Handling validations across associations in Rails

That’s kind of fun to say out loud.

Here’s a recent solution from Ryan Bates for handling validations across associations in Rails.

The key code is:

  validate :category_must_exist
 
  def category_must_exist
    errors.add(:category_id, "can't be blank") if category_id.blank?
  end

If you are new to how these custom validations work, here’s some more context.

class Post < ActiveRecord::Base
  belongs_to :category
 
  validates_presence_of :title
  validates_presence_of :permalink
  validates_uniqueness_of :permalink 
  validate :category_must_exist
 
  def category_must_exist
    errors.add(:category_id, "can't be blank") if category_id.blank?
  end
 
end

and my category model looks like this (so each post only has one category as of now.

class Category < ActiveRecord::Base
  has_many :posts
end

Comments