我假设您有两个 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_at 和 updated_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 文档中了解更多信息。