0

在我的情况下,如果用户连续提交,它将与垃圾邮件警报相匹配。
这工作正常。但它刷新了所有字段,所有字段都变为空。
我怎样才能避免这种情况?

控制器

    @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 %>
4

1 回答 1

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
于 2012-12-27T13:25:10.843 回答