i will assume that you have two ActiveModel's: User and Message. Make sure that you have classes like:
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
A small trivia when you add t.timestamps
to your migrations it creates created_at
and updated_at
fields for you.
Now I will just hard code the raw sql query for you:
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
You can play with order('created_at DESC')
in order if you just want in ascending order you can replace DESC with ASC or order(:created_at)
You may put any other query conditions also like not showing deleted messages etc. You can learn more from official Ruby on Rails document for Active Record Query Interface.