首页 > 解决方案 > DateTime 字段未正确更新

问题描述

我有一个对话模型,用于表示两个用户之间的对话。它有一些属性,两个是一个created_atupdated_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字段没有更新?

标签: rubysinatra

解决方案


推荐阅读