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
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
Post a Comment