【问题标题】:how can I display all users except current user and current_user's friends in ruby on rails如何在 ruby​​ on rails 中显示除当前用户和 current_user 的朋友之外的所有用户
【发布时间】:2014-10-20 03:47:57
【问题描述】:

我正在做一个加好友功能,在加好友页面,我想显示除当前用户和用户好友之外的所有用户,然后是一个“加”按钮。但我只能显示没有当前用户或用户朋友的所有用户。 这是我在用户模型中的代码:

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 和其他人,但没有看到朋友?
  • 这次出现错误,ActiveRecord::StatementInvalid in User#index SQLite3::SQLException: near "SELECT": syntax error: SELECT "users".* FROM "users" WHERE (id ! = 3 AND id != SELECT "users"."id" FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = ?)
  • 第一个结果相同,第二个也出错...SQLite3::SQLException: near ",": syntax error: SELECT "users".* FROM "users" WHERE ( id != 1,3)
  • 语法有点不对劲。我更新了我的答案。这就是你所需要的。试试看,让我知道。 :)

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


【解决方案1】:

如果您希望您的范围有多个条件,则不能使用&amp;&amp; 链接它们。

如果第一个返回真实值,那么这两个方法调用恰好按顺序调用,但只有最后一个会决定作用域的结果。

因此,您的第一个 where 在该范围内被完全忽略。尝试交换两个wheres,你会看到:当前用户被排除在外,但她的朋友却没有。

应该是:

scope :all_except, ->(user) { where.not(id: (user.friends + [user]).map(&:id))}

【讨论】:

    【解决方案2】:

    要显示不是 current_user 或 current_users_friends 的所有用户,这应该适合您:

    scope :all_except, ->(user) { where(["id NOT IN (?)", ([user.friends.map(&:id) << user.id]) ]) }
    

    【讨论】:

    • 如果它显示所有用户,那么您没有传递正确的 ID,您的错误仅显示两个 id 的 1,3。这段代码可以满足您的需要。您的问题在其他地方。
    【解决方案3】:

    试试这个:

    scope :all_except,
      ->(user) { where.not(id: user) && where.not(id: user.friends.map(&:id))}
    

    scope :all_except,
      ->(user) { where.not(id: user) && where.not(id: user.friends.select(:id))}
    

    【讨论】:

    • 和之前一样,当前用户还在
    • 我想@michael 说-&gt;(user) { where.not(id: user) &amp;&amp; where(id: user.friends.map(&amp;:id))} 试试看。
    • @fab 我试过你说的,但这次只显示用户的朋友。我想要的不是用户的朋友,也不是用户。
    • @jacobb 我误读了这个问题。我以为你只想要用户的朋友。在那种情况下,迈克尔的回答是正确的。也许您的关联设置不正确。更新您的问题并展示您的模型。
    【解决方案4】:

    试试这个:

    scope :all_except,->(user) {where.not(id: (user.friends.map(&:id) + user.id)}
    

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多