1

我正在尝试创建一个验证,以确保从 00:00 开始每天 24 小时发布一个帖子。请问如何在 Rails 中做到这一点?

我做了以下但我不知道把today方法放在哪里。更简单的替代品非常受欢迎。

def today
  where(:created_at => (Time.now.beginning_of_day..Time.now))
end

然后我在文章模型中添加了一个验证:

validate :time_limit, :on => :create

time_limit并在同一模型中定义,如下所示:

def time_limit
 if user.articles.today.count >= 1
 errors.add(:base, "Exceeds daily limit")
end

但是我在创建操作中不断收到“无方法”错误。

undefined method `today'

我不确定在哪里放置这个方法。

4

2 回答 2

3

您应该为此使用范围:

class Article
  scope :today, -> { where(:created_at => (Time.now.beginning_of_day..Time.now.end_of_day)) }
end

http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/scope

于 2013-07-21T19:58:58.493 回答
0

该错误是因为today是模型的实例方法,而不是范围。

你需要的是scope

 scope :today, lambda{ where(:created_at => (Time.now.beginning_of_day..Time.now)) }
于 2013-07-21T20:02:14.563 回答