I implemented similar functionality in mongoids and rails. The models were User, Friendship and Request. Its as a user sends a request to a friend to another user.
class User
include Mongoid::Document
include Mongoid::Timestamps
devise :invitable, :database_authenticatable, :registerable, :recoverable,
:rememberable, :trackable, :validatable, :confirmable
...
has_many :requests_from, class_name: "Request", inverse_of: :requested_by
has_many :requests_to, class_name: "Request", inverse_of: :requested_to
has_many :friendships, inverse_of: :owner
def friends
fs = Friendship.any_of({:friend_id.in => [self.id]}, {:owner_id.in => [self.id]}).where(state: 'accepted')
User.in(id: fs.collect{|i| [i.friend_id, i.owner_id]}.flatten - [self.id])
end
end
class Friendship
include Mongoid::Document
include Mongoid::Timestamps
field :state, type: String, default: 'pending'
field :pending, type: Boolean, default: true
belongs_to :owner, class_name: 'User'
belongs_to :friend, class_name: "User"
validates :state, inclusion: { in: ["pending", "accepted", "rejected"]}
...
end
class Request
include Mongoid::Document
include Mongoid::Timestamps
field :state, type: String, default: 'pending'
belongs_to :requested_by, class_name: 'User', inverse_of: :requests_from
belongs_to :requested_to, class_name: 'User', inverse_of: :requests_to
validates :state, inclusion: { in: ["pending", "accepted", "rejected"]}
...
end
Hope this helps.
source
share