如何在Rails中validation时间? 限制用户每天发布一次

我试图将用户的post限制为每天一次,我正在考虑检查Time.now – last_post_time是否<(一天中的第二个)但是那会强制每个帖子之间的24小时。

我想做的只是在这个月每天允许一个post,所以如果用户在3月28日发帖,他就不能再发帖到29日。 但如果他在3月28日晚上10点发布,他可以在3月29日上午12:01再次发布。

我该怎么办?

编辑:

这是我的posts_controller,我可以获得一些关于如何重构这个的帮助吗?

def create @post = current_user.posts.build(params[:supportpost]) if @post.save flash[:success] = "Your post was created!" redirect_to root_path else @feed_items = [] render 'pages/home' end end 

我正在尝试这样的事情,但肯定是错的:

  def create post = @user.posts.find(:first, :conditions => ["STRFTIME('%d', created_at) = ?", Date.today.day]) if post @post = current_user.posts.build(params[:supportpost]) if @post.save flash[:success] = "Your post was created!" redirect_to root_path else @feed_items = [] render 'pages/home' end end 

我可能会在Post模型中的validation中添加此检查。 也许是这样的:

 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 
 post = @user.posts.find(:first, :conditions => ["DATE(created_at) = DATE(?)", Time.now]) if post # he made a post today! else #he can post end 

总而言之,它产生了这个SQL查询:

  SELECT `posts`.* FROM `posts` WHERE (`posts`.user_id = 1) AND (DATE(created_at) = DATE('2011-03-29 04:35:45')) LIMIT 1