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

后端 未结 2 724
清歌不尽
清歌不尽 2020-12-30 14:55

I\'m trying to limit user\'s posts to once a day, I was thinking about checking if Time.now - last_post_time is < (second in a day) but then that would force a 24hour per

相关标签:
2条回答
  • 2020-12-30 15:23
    post = @user.posts.find(:first, :conditions => ["DATE(created_at) = DATE(?)", Time.now])
    if post
      # he made a post today!
    else 
      #he can post
    end
    

    So all in all, it produces this SQL query:

     SELECT `posts`.* FROM `posts` WHERE (`posts`.user_id = 1) AND (DATE(created_at) = DATE('2011-03-29 04:35:45')) LIMIT 1
    
    0 讨论(0)
  • 2020-12-30 15:29

    I would probably add this check in a validation in the Post model. Perhaps something like this:

    class Post < ActiveRecord::Base
      ...
    
      validate :date_scope
    
    private
      def date_scope
        if Post.where("user_id = ? AND DATE(created_at) = DATE(?)", self.user_id, Time.now).all.any?
          errors.add(:user_id, "Can only post once a day")
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题