如何在 Rails 中验证时间?限制用户每天发帖一次 [英] How do I validate a time in Rails? Limiting a user to post once a day
问题描述
我试图将用户的帖子限制为每天一次,我正在考虑检查 Time.now - last_post_time 是否 <(一天中的第二个)但是那样会强制每个帖子之间有 24 小时的时间间隔.
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.
我想做的是只允许一个月内每天发一个帖子,所以如果用户在 3 月 28 日发帖,他直到 29 日才能再次发帖.但如果他在 3 月 28 日晚上 10 点发帖,他可以在 3 月 29 日凌晨 12:01 再次发帖.
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.
我该怎么做?
这是我的posts_controller,我能得到一些关于如何重构它的帮助吗?
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
推荐答案
我可能会在 Post 模型的验证中添加此检查.也许是这样的:
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
这篇关于如何在 Rails 中验证时间?限制用户每天发帖一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!