Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 limit user created objects

I would like to limit the number of model Objects a user can create. I've tried the below but it is not working. I understand some changes have happened in rails 3.1 and not sure how to accomplish this now.

class User < ActiveRecord::Base
  has_many :things, :limit => 5, :dependent => :destroy # This doesn't work
end

class Things <ActiveRecord::Base
  belongs_to :user
end
like image 722
user892583 Avatar asked Oct 23 '11 00:10

user892583


2 Answers

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

like image 128
Alex Peattie Avatar answered Sep 29 '22 03:09

Alex Peattie


It did not work on Rails 3.2.1. Count always equals to 0. I have replaced it with self.user.things.size and now it works.

like image 40
sekrett Avatar answered Sep 29 '22 02:09

sekrett