RoR 3 Limiting users to 2 posts per day

后端 未结 1 1148
陌清茗
陌清茗 2020-12-28 23:59

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 hav

相关标签:
1条回答
  • 2020-12-29 00:32

    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
    
    0 讨论(0)
提交回复
热议问题