Rails 3.1 limit user created objects

Try something like this:

class User < ActiveRecord::Base
  has_many :things
end

class Things <ActiveRecord::Base
  belongs_to :user
  validate :thing_count_within_limit, :on => :create

  def thing_count_within_limit
    if self.user.things(:reload).count >= 5
      errors.add(:base, "Exceeded thing limit")
    end
  end
end

Edit: updated for Rails 3

Leave a Comment