我正在执行添加朋友功能,在“添加朋友”页面中,我想显示除当前用户和该用户的朋友以外的所有用户,然后单击“添加”按钮。但是我只能显示所有用户,没有当前用户或该用户的朋友。这是我在用户模型中的代码:
scope :all_except, ->(user) { where.not(id: user) && where.not(id: user.friends)}
这是用户控制器:
@users = User.all_except(current_user)
这是视图:
<% for user in @users %>
<div class="user">
<p>
<strong><%=h user.name %></strong>
<%= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post %>
<div class="clear"></div>
</p>
</div>
<% end %>
这样,用户的朋友将不会显示在页面上,但是当前用户的名称仍会显示在页面上。有人可以帮忙吗?谢谢!
我尝试更改代码(如果使用)
scope :all_except, ->(user) { where.not(id: user) && where.not(id: user.friends)}
where.not(id:user)不起作用,如果我使用
scope :all_except, ->(user) {where.not(id: user.friends) && where.not(id: user)}
where.not(id:user.friends)不起作用
要显示不是current_user或current_users_friends的所有用户,这应该对您有用:
scope :all_except, ->(user) { where(["id NOT IN (?)", ([user.friends.map(&:id) << user.id]) ]) }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句