message system in ruby on rails

1- Create message model:- 

rails g model message sender_id:integer recepient_id:integer body:text

2- Define Assosciation and scopes:- 

class Message < ActiveRecord::Base
    belongs_to :sender,
     :class_name => 'User',
     :foreign_key => 'sender_id'
    belongs_to :recepient,
     :class_name => 'User',
     :foreign_key => 'recepient_id'

    scope :conversations, lambda{|sender_id,recepient_id| where('sender_id = ? AND recepient_id = ? ',sender_id, recepient_id ).order("created_at DESC")}

    scope :friends_conversations, lambda{|recepient_id,sender_id| where('sender_id = ? AND recepient_id = ? ',sender_id, recepient_id ).order("created_at DESC")}
end

3- User model:-

class User < ActiveRecord::Base
 has_many :received_messages,
 :class_name => 'Message',
 :foreign_key => 'recepient_id'
 has_many :sent_messages,
 :class_name => 'Message',
 :foreign_key => 'sender_id'
end

4- Return Conversations:- 

conversations = Message.conversations(current_user.id,params[:friend_id])
        friends_conversations = Message.friends_conversations(current_user.id,params[:friend_id])
        render :json =>  { status: 200,:conversations => (conversations + friends_conversations).sort_by(&:created_at) }

5- Return messages:-
messages = user.received_messages
sent_messages = user.sent_messages



 

Comments

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Reading Excel Sheets using "Roo" gem in ruby on rails

Bootstrap Select Picker append add new item if search not exist

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails