Rails - 从 before_create 返回 false 可以防止对其他模型的更改

发布于 2024-09-04 09:05:24 字数 581 浏览 3 评论 0原文

我有一个 before_create 过滤器,用于检查人们是否发布了太多评论。

如果他们是,我想标记他们的帐户。

class Comment < ActiveRecord::Base
  before_create :check_rate_limit

  def check_rate_limit
    comments_in_last_minute = self.user.comments.count(:conditions => ["comments.created_at > ?", 1.minute.ago])
    if comments_in_last_minute > 2
      user.update_attribute :status, "suspended"
      return false
    end
    true
  end
end

before 过滤器返回 false 以阻止创建评论。问题是,这会触发回滚,这也会撤消我对用户模型所做的更改。

完成此任务的正确模式是什么?具体来说:每次创建对象时运行检查,并且在检查失败时能够编辑另一个模型。

I have a before_create filter that checks if people are posting too many comments.

If they are I want to flag their account.

class Comment < ActiveRecord::Base
  before_create :check_rate_limit

  def check_rate_limit
    comments_in_last_minute = self.user.comments.count(:conditions => ["comments.created_at > ?", 1.minute.ago])
    if comments_in_last_minute > 2
      user.update_attribute :status, "suspended"
      return false
    end
    true
  end
end

The before filter returns false to stop the comment from being created. The problem is that this triggers a ROLLBACK which also undoes the changes I made to the user model.

What's the correct pattern to accomplish this? Specifically: running a check each time an object is created and being able to edit another model if the check fails.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蒲公英的约定 2024-09-11 09:05:24

我认为限制速率的最佳方法是将请求排队并以最大允许速率读取它们。

标记过度使用的触发器只是队列中一定数量的请求。

它还具有不会立即影响后面的数据库的优点,因为它允许在更好的可控排队系统中将瓶颈移至数据库之前。这使得网站即使在“攻击”下也能保持响应。

这些队列可以像带有链表的哈希图一样简单。但如果可能的话,最好使用一些线程安全的 fifo

I think the best approach to rate limiting is queueing the requests and reading them at the maximal allowable rate.

The trigger to flag overuse the simply becomes a set number of requests in the queue.

It also has the advantage of not immediately impacting on your database behind as it allows to move the bottleneck before the database in a better controllable queueing system. This allows hte site to remain responsive even under "attack".

These queues can be as simple as a hashmap with a linked list. But better use some threadsafe fifo if avilable

很快妥协 2024-09-11 09:05:24

这不是一个理想的答案,但现在即使帐户被暂停,我最终也只是返回 true。这样一来,又有一个人经历了,但未来的人却没有。

This isn't an ideal answer but for now I ended up just returning true even when the account was suspended. This way one more went through, but future ones did not.

孤者何惧 2024-09-11 09:05:24

对我来说,似乎在回调中返回 false 并不会停止返回记录,即使它没有保存到数据库中,很奇怪。

for me it seems like returning false in the callback doesn't stop returning the record, even though it is not saved onto the database, weird.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文