Rails - 是@user的current_user朋友吗?

时间:2015-08-04 02:56:46

标签: ruby-on-rails activerecord rails-activerecord

我正在慢慢实现向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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您可以像这样定义def friend_with?(other_user) friendships.find_by(friend_id: other_user.id) end

current_user.friend_with? some_user

然后,您可以使用Swift确认这两个用户是否是朋友。

希望它有所帮助!