【问题标题】:how to select all users except for the current user如何选择除当前用户之外的所有用户
【发布时间】:2018-10-26 12:37:23
【问题描述】:

我想在索引页面上列出除当前用户之外的所有用户。我试图制作一个“关注的人”功能,显然当前用户不能在该列表中。我当前的代码如下。我正在使用设备,我假设类似@users = User.where(user: != current_user).limit(5) 或类似的东西。

推文控制器,索引:

@users = User.all.limit(5)

索引页面:

<h3 class="text-primary sides-title">Explore</h3>
<% @users.each do |user| %>
  <div class="user_card">
     <p class="users_username text-primary"><%= user.username %></p>
     <%=  cl_image_tag user.photo, height: 60, width: 60, crop: :fill, class: "users_photo" %>
     <%= link_to "Check'em out!", user_path(user), class: "user_button" %>
  </div>
<% end %>

【问题讨论】:

  • User.where.not(id: current_user.id)

标签: ruby-on-rails ruby


【解决方案1】:

User.where(user: != current_user) 是无效语法,对于 SQL 比较运算符,您可以提供一个字符串作为 where 的参数:

User.where('user_id != ?', current_user.id) # binding the argument provided

或者只是User.where.not(id: current_user.id)

【讨论】:

  • 谢谢你的作品!我使用了User.where.not(id: current_user.id)。但是有没有办法将limit(5)添加到最后。我试过但说语法无效。
  • 你能说明你遇到了什么错误吗?您是如何尝试添加限制的?
【解决方案2】:

对于 Rails 4+ 表示法:

allcurrent_user以外的用户

User.where.not(id: current_user.id)

current_userlimit 以外的用户

User.where.not(id: current_user.id).limit(5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2014-08-28
    • 2015-12-04
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多