我制作了一个简单的Rails应用程序,允许人们对帖子发表评论。如何阻止该用户一遍又一遍地提交该表单?在reddit.com上,他们只允许新用户每十分钟发一次新帖子。我如何使用简单的博客/评论系统来完成这项工作?任何帮助将不胜感激。感谢您阅读我的问题。 编辑:我试图在没有用户模型的情况下完成此任务。
这是我目前的评论控制器:
class CommentsController < ApplicationController
# before_filter :require_user, :only => [:index, :show, :new, :edit]
before_filter :post_check
def record_post_time
cookies[:last_post_at] = Time.now.to_i
end
def last_post_time
Time.at((cookies[:last_post_at].to_i rescue 0))
end
MIN_POST_TIME = 2.minutes
def post_check
return true if (Time.now - last_post_time) > MIN_POST_TIME
# handle error
# flash("Too many posts")
end
def index
@message = Message.find(params[:message_id])
@comments = @message.comments
end
def show
@message = Message.find(params[:message_id])
@comment = @message.comments.find(params[:id])
end
def new
@message = Message.find(params[:message_id])
@comment = @message.comments.build
end
def edit
@message = Message.find(params[:message_id])
@comment = @message.comments.find(params[:id])
end
def create
@message = Message.find(params[:message_id])
@comment = @message.comments.build(params[:comment])
#@comment = Comment.new(params[:comment])
if @comment.save
record_post_time#
flash[:notice] = "Replied to \"#{@message.title}\""
redirect_to(@message)
# redirect_to post_comment_url(@post, @comment) # old
else
render :action => "new"
end
end
def update
@message = Message.find(params[:message_id])
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
record_post_time
redirect_to post_comment_url(@message, @comment)
else
render :action => "edit"
end
end
def destroy
end
end
答案 0 :(得分:2)
试试这个:
class CommentsController < ApplicationController
before_filter :post_check
def record_post_time
cookies[:last_post_at] = Time.now.to_i
end
def last_post_time
Time.at((cookies[:last_post_at].to_i rescue 0))
end
MIN_POST_TIME = 2.minutes
def post_check
return true if (Time.now - last_post_time) > MIN_POST_TIME
flash[:notice] = "Too many comments makes you a busy cat!"
@message = Message.find(params[:message_id])
redirect_to(@message)
return false
end
def create
@comment = Comment.new(params[:comment])
if @comment.save
record_post_time
else
end
end
def update
@comment = Comment.find(parms[:id])
if @comment.update_attributes(params[:comment]))
record_post_time
else
end
end
end
答案 1 :(得分:1)
在你的评论课中你可以这样做:
validate :posting_too_often
def posting_too_often
c = self.post.comments.find_by_user_id(self.user_id, :limit => 1, :order => 'created_at desc')
if c && c.created_at > 10.minutes.ago
self.errors.add_to_base("stop posting so many crappy comments!")
end
end
这可能不起作用,因为我没有测试它,但它应该向你发送正确的方向。你在做什么:
在创建评论之前,请加载该用户的最后一条评论。如果它存在且在过去10分钟内发布,则向基础添加错误,并解释无法保存的原因。
我希望这有帮助!