0

Hello i'm new to rails

I have a table named 'messages' which has columns current_user__id , to_user_id and created time

I am trying to build a chat application where different users can chat individually and those message will be stored at messages table with their respective ids.

Now in order to print the messages on screen.

I'm facing issues

I need a query such that both the current_user__id and to_user_id conversations and to_user_id and current_user__id conversation will be listed by the latest created time.

Manjula Mv
  • 31
  • 7

1 Answers1

1

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.

Muhammed Kılıç
  • 1,271
  • 1
  • 7
  • 21