Rails:新记录创建验证的速度

时间:2017-10-28 03:42:54

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

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

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

非常感谢。

1 个答案:

答案 0 :(得分:2)

一种简单的方法可以在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

希望这会给你一个想法。怎么做。

相关问题