Rails 为什么我都过滤了 new,create,还是能被别人发了垃圾信息?

Zoker · 2014年04月14日 · 最后由 zoker 回复于 2014年04月15日 · 3200 次阅读

先是 before_filter :authorize_post!, only: [:new, :create] 然后是

protected

def authorize_post!
   if @forum.id < 6
      redirect_to posts_url, alert: "此板块不允许发帖"
   elsif DateTime.parse(Time.now.to_s) - DateTime.parse(current_user.created_at.to_s) < 7
      unless Post.where("author_id = #{current_user.id} AND to_days(created_at) = to_days(now()) ").count < 5
        redirect_to posts_url, alert: "未满一周用户每天只能发5篇帖子"
      end
    end
end

我自己测试都没有问题,符合条件得都 redirect_to 我定义得地址了,但是为什么还是有人可以无穷无尽的发?

更新呢?

#1 楼 @winnie 更新也需要么?没有限制更新会导致可以发很多?

正常来说更新是不需要,因为更新需要现有的 id,没有 id 会出错。

可能 condition 有问题吧,最好多贴点具体细节。

#3 楼 @billy 贴出来了。我自己测试是一切正常的,但是不知道别人是从哪个地方能发这么多的。

问题是 redirect_to 用在这里好不好,感觉还是先返回 true,false 会比较好,alert 放在暂存里。

redirect_to posts_url, alert: "此板块不允许发帖" if @forum.id < 6
is_new_user = Time.now < (current_user.created_at + 7.days)
today_posts_count = Post.where("author_id = ? AND created_at >= ?", current_user.id, Time.now.at_beginning_of_day).count if is_new_user
redirect_to posts_url, alert: "未满一周用户每天只能发5篇帖子" if is_new_user and today_posts_count >= 5
true

发贴的是注册用户还是非注册用户?

#5 楼 @5swords 是不是 return 的问题,这样写:

return redirect_to posts_url

s 是不是就能解决这个问题了?

@kesin 那就是 return 的问题,你的 redirect 没有 return, 所以 action 会一直执行下去直到 render。那么用户看到的 url 就是 redirected url, 但是内容却是 new。create也是一样,不会阻止,直到 post created。

#5 楼 @5swords 跟这个无关

If a "before" filter renders or redirects, the action will not run

http://guides.rubyonrails.org/action_controller_overview.html#filters

应该不是这个问题,我把 validate 搞混了。应该是你的 before_filter 里逻辑的问题。

这个代码有问题: DateTime.parse(Time.now.to_s) - DateTime.parse(current_user.created_at.to_s) < 7

改成 (Time.now - current_user.created_at) < 7.days

能看看你的网站吗?

#10 楼 @Rei 估计是这个问题。

@forum.id=7 然后更新为 forum.id=6 呢??

建议你查看一下日志,看看用户创建的时候传的参数情况

#16 楼 @cwheart #14 楼 @cisolarix #12 楼 @quakewang #10 楼 @Rei thx all your guys 重新写了 condition,然后 redirect_to 是这样写的return redirect_to ……………… 没问题了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号