Max Rose-Collins
Max Rose-Collins

Reputation: 1924

Ruby on Rails - Limit a user to a set number of database entries

I want to limit the amount of records a user can add to the database.

I'm not sure of the 'Rails' way to go about this...

I am using Devise and thought of creating a custom validation method but you can't access current_user from within a model and it isn't correct.

How can I do this from the controller and still return an error message to my users?

I had this

 validate :post_count

  def post_count
    current = current_user.posts.count
    limit = current_user.roles.first.posts.count

    if current > limit
      errors.add(:post, "Post limit reached!")
    end
  end

but it isn't the correct way to go about it as it would be hacky to get the current_user into the model

Upvotes: 3

Views: 2930

Answers (1)

backpackerhh
backpackerhh

Reputation: 2353

You could do something like this:

class User < ActiveRecord::Base
  has_many :domains
  has_many :posts, through: :domains

  def post_limit
    roles.first.posts.count
  end
end

class Domain < ActiveRecord::Base
  belongs_to :user
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :domain
  delegate :user, to: :domain
  validate :posts_count_within_limit, on: :create

  def posts_count_within_limit
    if self.user.posts(:reload).count >= self.user.post_limit # self is optional
      errors.add(:base, 'Exceeded posts limit')
    end
  end
end

Based on this answer.

Upvotes: 4

Related Questions