在我的情况下,如果用户连续提交,则会与垃圾邮件提醒相匹配 这工作正常。但它会刷新所有字段并且所有字段都变空 我怎么能避免这个?
控制器
@user = User.find_by_username(params[:id])
@post = @user.comment_threads.last
if @post
last_time = @post.created_at
if Time.now - last_time <= 10.second
redirect_to :controller => 'users', :action => 'show', :id => @user.username
flash[:notice] = "You cannot spam!"
return
end
end
@user_who_commented = current_user
@comment = Comment.build_from( @user, @user_who_commented.id, params[:users][:body] )
@comment.comment_icon = params[:users][:comment_icon]
@comment.save
redirect_to :controller => 'users', :action => 'show', :id => @user.username
flash[:notice] = "comment added!"
查看
<%=form_for :users, url: url_for( :controller => :users, :action => :add_comment ) do |f| %>
<div class="field">
<%= f.label :body %><br />
<%= f.text_field :body %>
</div>
<div class="field">
<%= f.file_field :comment_icon %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:1)
您应该将垃圾邮件控制逻辑移至模型。
validate :spam_validation
def spam_validation
if !user_id.blank?
post = user.comment_threads.last
last_time = post.created_at
if Time.now - last_time <= 10.second
errors.add(:base, "You cannot spam!")
end
end
end