rails自引用加入关联

问题描述 投票:0回答:2

我正在开发一个仅限API的应用程序,我试图模仿社交媒体功能。喜欢向用户发送请求,接受/拒绝请求,与朋友聊天。通过引用这个screen-cast,现在我可以添加其他用户作为朋友。

贝娄是我的用户模型

class User < ApplicationRecord
  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end

贝娄是友谊模特

class Friendship < ApplicationRecord
  belongs_to :user
  belongs_to :friend, :class_name => 'User'
end

我已经定义了路由,以便访问当前用户

  resources :users do
    resources :friendships, only: [:create, :destroy]
  end

我可以添加朋友如下

current_user = User.find(params[:user_id])
requesting_user = User.find(params[:req_user_id])
current_user.friends << requesting_user

一切都很好,直到这里。

任何人都可以建议我如何接受/拒绝请求?

我尝试了,还有一个FriendRequest模型,并决定是否添加请求作为朋友。但无法成功完成。

ruby-on-rails ruby ruby-on-rails-5
2个回答
1
投票

FriendRequest模型是一个不错的选择。

您还可以尝试将状态添加到友谊(请求,接受等)并在模型中定义范围以过滤请求或朋友。


1
投票

我会在Friendship模型中添加一个标志 - accepted boolean。然后我会添加默认范围:

../friendship.rb default_scope where(accepted: true)

对于待处理的好友列表,创建范围:

../user.rb has_many :pending_firends, through: :friendship do def pending where("friendships.accepted = ?", false) end end

我会说拒绝=删除友谊记录。您可以添加其他功能 - 已阻止。

current_user.friends

current_user.pending_firends

但是你想要成立,所以使用:

../friendship.rb scope :accepted, where(accepted: true) scope :pending, where(accepted: false)

../user.rb has_many :pending_firends, -> { pending }, through: :friendship has_many :accepted_firends, -> { accepted }, through: :friendship

它应该工作,我可能会犯一些错误。

© www.soinside.com 2019 - 2024. All rights reserved.