Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 458
trying_hal9000 Avatar asked Mar 29 '11 03:03

trying_hal9000


2 Answers

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
like image 170
DanneManne Avatar answered Oct 29 '22 21:10

DanneManne


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
like image 44
Mike Lewis Avatar answered Oct 29 '22 22:10

Mike Lewis