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
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
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