Search code examples
ruby-on-railstimelimit

RoR 3 Limiting users to 2 posts per day


I am looking for away to limit my users from posting more than twice per day and have no more than 5 posts per week. I have a users and posts model/controller.

I have been looking at these questions but they are not quite what I am looking for.

Rails 3.1 limit user created objects

How do I validate a time in Rails? Limiting a user to post once a day

Error @ 20:44 13/03/2012 with the code from KandadaBoggu

NoMethodError in PostsController#create

undefined method `beginnning_of_day' for 2012-03-13 20:36:11 +0000:Time

Solution

  • Try this:

    class User
      has_many :posts do
    
        def today
          where(:created_at => (Time.zone.now.beginning_of_day..Time.zone.now))
        end
    
        def this_week
          where(:created_at => (Time.zone.now.beginning_of_week..Time.zone.now))
        end
      end    
    end
    
    
    class Post
      belongs_to :user
    
      validate :user_quota, :on => :create  
    
    private 
      def user_quota
       if user.posts.today.count >= 2
         errors.add(:base, "Exceeds daily limit")
       elsif user.posts.this_week.count >= 5
         errors.add(:base, "Exceeds weekly limit")
       end
      end
    
    end