How do I validate a time in Rails? Limiting a user

2019-02-05 04:53发布

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 period between each post.

What'd I'd like to do is just allow one post per day in the month, so if user posts on the 28th of march he cannot post again until the 29th. But if he posted at 10pm on march 28th he could post again at 12:01am on march 29th.

How would I do this?

Edit:

Here is my posts_controller, can I get some help on how to refactor this?

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

I was trying something like this but it certainly is wrong:

  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

2条回答
祖国的老花朵
2楼-- · 2019-02-05 05:36

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
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-05 05:45
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
查看更多
登录 后发表回答