我如何每天validation一篇post?
我正在尝试创建一个validation,以确保每天发布一个post,从00:00开始24小时。 怎么能在Rails中完成呢?
我做了以下但我不知道在哪里放today
方法。 更简单的替代品非常受欢迎。
def today where(:created_at => (Time.now.beginning_of_day..Time.now)) end
然后我在文章模型中添加了validation:
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'
我不确定在哪里放这种方法。
你应该使用范围:
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
这个错误是因为today
是模型的实例方法,而不是范围。
你需要的是scope
:
scope :today, lambda{ where(:created_at => (Time.now.beginning_of_day..Time.now)) }