I want to create users dialog
How I must do?
Create one record with sender_id and recipient_id and then "select * from table_dialog where sender_id=current.id or recipient_id =current.id" also add 2 columns deleted_by_sender and deleted_by_recipient
Or create 2 record in开发者_运维百科 database for each dialog
What is the best solution? Or propose your own solution please
If by "dialog" you mean a "conversation between TWO participants", then it is very similar to classic mailbox. The following code extract(with abbreviation) from one of my project which implements similar functionality. Maybe will be helpful.
class User < ActiveRecord::Base
# ....
has_many :received_messages, :class_name => "Message", :foreign_key => 'recipient_id'
has_many :sent_messages, :class_name => "Message", :foreign_key => 'sender_id'
# ....
end
class Message < ActiveRecord::Base
validates :content, :presence => true
validates :sender, :presence => true, :associated => true
validates :recipient, :presence => true, :associated => true
belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
belongs_to :recipient, :class_name => 'User', :foreign_key => 'recipient_id'
default_scope order('created_at desc')
# usage: user.received_messages.unread
scope :unread, where('unread = true')
def self.chat_between(first_user, second_user)
where('(recipient_id = ? AND sender_id = ?) OR (recipient_id = ? AND sender_id = ?)',
first_user.id, second_user.id, second_user.id, first_user.id)
end
def self.read_all!
self.update_all('unread = false')
end
def read!
self.update_attribute :unread, false
end
def new?(user)
(recipient == user) && (unread == true)
end
end
精彩评论