【问题标题】:Ruby on rails data fetching issueRuby on rails 数据获取问题
【发布时间】:2021-04-01 02:12:02
【问题描述】:

你好,我是 Rails 新手

我有一个名为 'messages' 的表,其中包含 current_user__id 、 to_user_id 和 created time 列

我正在尝试构建一个聊天应用程序,让不同的用户可以单独聊天,并且这些消息将使用各自的 ID 存储在消息表中。

现在为了在屏幕上打印消息。

我遇到了问题

我需要一个查询,以便 current_user__id 和 to_user_id 对话以及 to_user_id 和 current_user__id 对话都将按最新创建时间列出。

【问题讨论】:

    标签: mysql ruby-on-rails-5 ruby-on-rails-6.1


    【解决方案1】:

    我假设您有两个 ActiveModel:用户和消息。确保你有这样的类:

    class User < ApplicationRecord
      has_many :messages
    end
    
    class Message < ApplicationRecord
      belongs_to :current_user, class_name: 'User', foreign_key: 'current_user_id'
      belongs_to :to_user, class_name: 'User', foreign_key: 'to_user_id'
    end
    

    当您将 t.timestamps 添加到迁移时,它会为您创建 created_atupdated_at 字段。

    现在我将为您硬编码原始 sql 查询:

      def get_messages(current_user_id, to_user_id)
        @messages = Message.where(' current_user_id=? OR receiver_user_id=? OR current_user_id=? OR receiver_user_id=? ', 
                    current_user_id, current_user_id, to_user_id, to_user_id).order('created_at DESC')
      end
    
    

    您可以按顺序使用order('created_at DESC'),如果您只想按升序排列,可以将DESC 替换为ASC 或order(:created_at)

    您可以设置任何其他查询条件,例如不显示已删除的消息等。您可以从Active Record Query Interface 的官方 Ruby on Rails 文档中了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多