ruby - DateTime 字段未正确更新
问题描述
我有一个对话模型,用于表示两个用户之间的对话。它有一些属性,两个是一个created_at
和updated_at
字段,我想使用该updated_at
字段来对对话列表从最近到最近进行排序。
然而,我遇到的问题是updated_at
时间没有正确更新,即使我自己更新。
对话.rb
class Conversation < CollectionModel
self.subtype = :conversation
field :id, type: String
field :uuid, type: String
field :participants, type: Array
field :messages, type: Array
field :created_at, type: DateTime
field :updated_at, type: DateTime
def initialize(properties={})
super(properties)
end
# Set the conversation participants
def set_participants(user1, user2)
self.participants = [user1, user2]
end
# Add a message to the conversation
def add_message(message, owner)
self.messages << Message.new(message, owner)
self.updated_at = Time.now
end
在我的 conversation_routes 中,我设置了两条路由,一条尝试查找现有对话(如果没有,则创建一个),另一条添加消息(应该更新updated_at
字段)
对话路由.rb
get '/:id/?' do
@conversation = Conversation.find(_id: params[:id])
if !@conversation
participants = params[:id].split('-')
@conversation = Conversation.new(id: params[:id],
uuid: SecureRandom.uuid,
participants: [participants[0], participants[1]],
messages: [],
created_at: Time.now,
updated_at: Time.now)
@conversation.save!
end
haml :'conversations/conversation'
end
post '/:id/sendmessage/?' do
@conversation = Conversation.find(_id: params[:id])
puts "Previous Time: #{@conversation.updated_at.strftime("%H:%M:%S")}"
puts "Adding message to conversation: #{params[:message]}"
@conversation.add_message(params[:message], current_user.id)
@conversation.update!
puts "New Time: #{@conversation.updated_at.strftime("%H:%M:%S")}"
redirect back
end
这些打印语句准确地打印出时间,即
Previous Time: 17:40:42
New Time: 17:41:44
并根据另一条消息:
Previous Time: 17:41:44
New Time: 17:45:12
。但是当我尝试打印出@conversations
自己(current_user.conversations)时,时间永远不会更新,所以它总是说
[{"id":"u1-u2","created":"2021-11-07 17:40:42 UTC","updated":"2021-11-07 17:40:42 UTC","type":"conversation","uuid":"92e4894c-73bb-4370-926f-1828c4b44ac4","participants":["u1","u2"],"messages":[],"created_at":"2021-11-07 17:40:42 UTC","updated_at":"2021-11-07 17:40:42 UTC"}]
为什么我的updated_time
字段没有更新?
解决方案
推荐阅读
- javascript - 如何修复“位置 0 的 JSON 中的意外令牌 <”?
- android - 安迪模拟器上的查尔斯代理问题(失败:SSLHandshake:不支持的curveId:29)
- c - 语言 C、TCP 服务器和客户端
- python - ModuleNotFoundError:没有名为“scrapy_user_agents”的模块
- html - 想要使用 HTML 5 数据属性显示方法返回
- python - 如何使用 BeautifulSoup 抓取隐藏的数据元素
- css - flexbox 让内容消失
- curl - 连接 curl 脚本输出“* 来自服务器的空回复”,但 Fiddler 可以获取数据
- elasticsearch - 使用源过滤器从热门点击聚合中排除内部点击
- reactjs - React 路由器不渲染路由,但设置了路径变量