【问题标题】:Rails: Speed of new record creation validationRails:新记录创建验证的速度
【发布时间】:2018-04-09 16:58:40
【问题描述】:

有没有办法在控制器中强制执行验证时间?例如,如果用户创建一个帖子,他们必须等待 5 秒才能创建另一个

我想在控制器中执行此操作,因为它显然只是对 current_user 的验证。

非常感谢。

【问题讨论】:

  • 简短的回答是“是”。
  • 另一个简短的回答。您在数据库级别或 Rails 应用程序级别设置了超时,当数据库执行时间超过超时时,它会出错。我认为在数据库级别执行此操作以拥有 1 个事实来源是有意义的。
  • 我建议向模型添加验证。

标签: ruby-on-rails ruby validation model-view-controller


【解决方案1】:

一个简单的方法是在before_action

before_action :check_minimum_time_to_create_post, only: [:create]

def create
  ...
end

private

def check_minimum_time_to_create_post
  last_post = current_user.posts.last
  if last_post && last_post.created_at - Time.now <= 5.seconds
    redirect_to error_page
  end
end

但我建议在模型中这样做:

class Post < ApplicationRecord
  validate :check_minimum_time_to_create_post, on: :create

  def check_minimum_time_to_create_post
    last_post = self.user.posts.last
    if last_post && last_post.created_at - Time.now <= 5.seconds
      errors[:base] << "The minimum time to create another post is xyz..."
    end
  end
end

希望这能给你一个想法。如何做到这一点。

【讨论】:

  • 谢谢!不幸的是,在模型验证中我得到了这个错误: undefined method `-' for nil:NilClass
  • 为 NIL,因为 last_post.created_at 在内存中但还没有 created_at 字段...为 NIL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多