rails自引用加入关联

时间:2018-02-06 16:17:23

标签: ruby-on-rails ruby ruby-on-rails-5

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

Bellow是我的用户模型

HTTP

贝娄是友谊模特

HTTPS

我已经定义了下面的路线来访问当前用户

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 模型,然后决定是否将请求添加为朋友。但无法成功完成。

2 个答案:

答案 0 :(得分:1)

FriendRequest模型是个不错的选择。

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

答案 1 :(得分:1)

我会向Debugger模型添加一个标志 - Friendship布尔值。 然后我会添加默认范围:

../ friendship.rb accepted

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

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

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

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

current_user.friends

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

../ friendship.rb current_user.pending_firends

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

应该有用,我可能会犯一些错误。