我正在慢慢实现向Rails应用添加和删除朋友的功能,但我很难更改"添加朋友"按钮到"删除朋友"反之亦然,具体取决于current_user
是否是当前正在查看的@user
个人资料的朋友。
这是我到目前为止user.rb
模型中的内容(this answer对另一个问题的礼貌):
has_many :friendships
has_many :passive_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :active_friends, -> { where(friendships: { approved: true}) }, :through => :friendships, :source => :friend
has_many :passive_friends, -> { where(friendships: { approved: true}) }, :through => :passive_friendships, :source => :user
has_many :pending_friends, -> { where(friendships: { approved: false}) }, :through => :friendships, :source => :friend
has_many :requested_friendships, -> { where(friendships: { approved: false}) }, :through => :passive_friendships, :source => :user
def friends
active_friends | passive_friends
end
def friend_with?(user)
# ... How would I go about this?
end
非常感谢任何帮助。
答案 0 :(得分:3)
您可以像这样定义def friend_with?(other_user)
friendships.find_by(friend_id: other_user.id)
end
:
current_user.friend_with? some_user
然后,您可以使用Swift
确认这两个用户是否是朋友。
希望它有所帮助!