先是
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 我定义得地址了,但是为什么还是有人可以无穷无尽的发?
问题是 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
@kesin 那就是 return 的问题,你的 redirect 没有 return, 所以 action 会一直执行下去直到 render。那么用户看到的 url 就是 redirected url, 但是内容却是 new。create
也是一样,不会阻止,直到 post created。
If a "before" filter renders or redirects, the action will not run
http://guides.rubyonrails.org/action_controller_overview.html#filters
这个代码有问题: DateTime.parse(Time.now.to_s) - DateTime.parse(current_user.created_at.to_s) < 7
改成 (Time.now - current_user.created_at) < 7.days
#16 楼 @cwheart
#14 楼 @cisolarix
#12 楼 @quakewang
#10 楼 @Rei
thx all your guys
重新写了 condition,然后 redirect_to 是这样写的return redirect_to ………………
没问题了