5

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
Community
  • 1
  • 1
Steve
  • 438
  • 5
  • 11

1 Answers1

19

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
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
  • Thanks KandadaBoggu. I have added your code and restarted the rails server and now when I'm posting I get the error posted above – Steve Mar 13 '12 at 20:43
  • There was a typo in my answer. Try now. – Harish Shetty Mar 13 '12 at 21:02
  • Thanks KandadaBoggu, this time I am getting this error "undefined method `Time' for 2012-03-13 21:19:00 +0000:Time" – Steve Mar 13 '12 at 21:20
  • 2
    While I fixed the typo, I introduced a copy+paste error. Code should work now. PS: You should be able to fix such simple syntax errors by yourself. – Harish Shetty Mar 13 '12 at 22:08
  • Thanks KandadaBoggu its working. I should have spotted the typo too "nnn" Its one of those days today.. – Steve Mar 13 '12 at 22:21