首页 > 解决方案 > 如何隐藏已添加为好友的好友?

问题描述

我有以下代码。添加朋友部分效果很好。但之后我仍然看到“添加朋友”按钮。所以我添加了 <% if... 部分,但 @friendship 呈现错误(下面的控制器代码),所以我添加了 <% @friendships.each do... 部分。还是不行;每个用户节目上都有许多“添加朋友”。

<% @friendships.each do |friendship|%>
  <% if current_user.id != friendship.user_id and post.book.user_id != friendship.friend_id %>
    <%= link_to "Add Friend", friendships_path(:friend_id => post.book.user_id), :method => :post %>
  <% end %> 
<% end %>

控制器:

@friendship = Friendship.where(friend_id: params[:user_id])
@friendships = Friendship.all

我怎样才能解决这个问题?撤消迁移并安装 has_friendship gem(撤消,因为 gem 和我当前的实现都使用“友谊”模型)会更好吗?

友谊模型:

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

标签: ruby-on-railsruby

解决方案


正如所写的那样,您似乎正在遍历数据库中存在的每一个友谊。你只需要遍历当前用户的好友。

这不仅是一个小得多的列表,而且该列表中的每个成员都已经是朋友,您不必询问是否应该显示“添加朋友”链接。

考虑以下。

首先,我们以稍微不同的方式重述模型:

class Connection < ApplicationRecord
  belongs_to :user
  belongs_to :friend, class_name: "User"
end

class User < ApplicationRecord
  has_many :connections
  has_many :friends, through: :connections, class_name: "User"
end

接下来,我们做一些用户:

Loading development environment (Rails 6.0.2.1)
irb(main):001:0> ['User One', 'User Two', 'User Three' ].each { |u| User.create(name: u) }
...
=> ["User One", "User Two", "User Three"]
irb(main):002:0> users = User.all
...
irb(main):003:0> users.size
...
=> 3
irb(main):004:0>

然后,我们连接一些用户:

irb(main):004:0> Connection.create(user: User.first,  friend: User.second)
irb(main):005:0> Connection.create(user: User.second, friend: User.first)
irb(main):006:0> Connection.create(user: User.second, friend: User.third)
irb(main):007:0> Connection.create(user: User.third,  friend: User.second)

现在,我们可以像这样显示特定用户的朋友:

<% @user.friends.each do |friend| %>
  <% friend.name %>
  ...
<% end %>

推荐阅读