我正在寻找限制我的用户每天发布超过两次并且每周不超过5个帖子。我有一个用户和帖子模型/控制器。
我一直在看这些问题,但它们并不是我想要的。
Rails 3.1 limit user created objects
How do I validate a time in Rails? Limiting a user to post once a day
错误@ 20:44 13/03/2012,来自KandadaBoggu的代码
NoMethodError in PostsController#create
undefined method `beginnning_of_day' for 2012-03-13 20:36:11 +0000:Time
答案 0 :(得分:18)
试试这个:
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