gpt4 book ai didi

ruby-on-rails - 如何在RoR中正确查询当前用户在指定时间范围内发送的所有消息?

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:46 28 4
gpt4 key购买 nike

我是一名 Ruby 初学者。我正在尝试编写一个函数(在 Rails 应用程序中),该函数可能允许或不允许用户发送消息,具体取决于他们当前的每日配额。我在消息 Controller 中调用此函数,而它是在消息模型中定义的。

函数定义:

def limit_has_been_reached(user)
limit = 50
messages = user.messages.find(:all, :conditions => ["created_at between ? and ?",
Date.today - 1.day, Date.today])
if messages.length < limit
return false
else
return true
end
end

函数调用:

def create
...
if !@message.limit_has_been_reached(current_user)
send
else
reject

这就是我目前所拥有的。我的问题是,函数总是返回 false。经过检查,我注意到查询总是返回一个空数组。以下是它在 Rails 控制台中运行时的作用:

Message Load (0.4ms)  SELECT `messages`.* FROM `messages` WHERE `messages`.`user_id` = ? AND (created_at between '2014-01-30' and '2014-01-31')  [["user_id", 1]]

这是示例中的用户 (id = 1) 在该时间范围内发送的许多消息。任何人都可以阐明为什么会发生这种情况吗?谢谢

编辑:将函数定义中的第 4 行更改为 Date.today - 1.day, DateTime.now 有效。

最佳答案

我建议你创建一个范围:

class User < ActiveRecord::Base
scope :reached_limit, -> (self, limit) {
self.messages.where(created_at: Date.beginning_of_day..Date.end_of_day).count >= limit
}
end

那就这样使用吧。

def create
if current_user.limit_has_been_reached?(limit)
# ...
end

您可能希望将 limit 存储在此 User 类的一个常量或属性中。

关于ruby-on-rails - 如何在RoR中正确查询当前用户在指定时间范围内发送的所有消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com