[英]withhold current user from an index of all users in a ruby on rails app
I am working away at one of my first Ruby on Rails CRUD type apps. 我正在研究我的第一个Ruby on Rails CRUD类型的应用程序。
It is an Instagram like application with users accounts (Devise) and pictures uploaded and owned by users. 这是一个类似Instagram的应用程序,具有用户帐户(Devise)以及用户上传和拥有的图片。
I would like to create an index of users, a Discover Other Users feature. 我想创建一个用户索引,一个“发现其他用户”功能。 I have done this, but the output includes the currently logged in User.
我已经做到了,但是输出包括当前登录的用户。 I wish to omit the current user from the index of users under Discover Other Users.
我希望在“发现其他用户”下的用户索引中省略当前用户。
User Controller Code with the code I tried, unsuccessfully, commented out. 用户控制器代码以及我尝试的代码未成功注释掉。
class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new end def index @users = User.all #@users = User.where("user_id != ?", current_user.id) end end
User View Code 用户查看代码
<div class="booyah-box col-xs-6 col-xs-offset-3"> <% @users.each do |user| %> <%= link_to public_profile_path(user) do %> <%= image_tag user.avatar, :class => "smallPlate" %> <% end %> <% end %> </div>
and the Error 和错误
ActiveRecord::StatementInvalid in Users#index Showing /vagrant/src/platewarz/app/views/users/index.html.erb where line #2 raised: PG::UndefinedColumn: ERROR: column "user_id" does not exist LINE 1: SELECT "users".* FROM "users" WHERE (user_id != 9) ^ : SELECT "users".* FROM "users" WHERE (user_id != 9) Extracted source (around line #2): 1 2 3 4 5 <div class="booyah-box col-xs-6 col-xs-offset-3"> <% @users.each do |user| %> <%= link_to public_profile_path(user) do %> <%= image_tag user.avatar, :class => "smallPlate" %> <% end %> Rails.root: /vagrant/src/platewarz Application Trace | Framework Trace | Full Trace app/views/users/index.html.erb:2:in `_app_views_users_index_html_erb___484529272__626771048'
If you are using Rails 4: 如果您使用的是Rails 4:
@users = User.where.not(id: current_user.id)
else 其他
@users = User.where('id != ?', current_user.id)
Something off the topic: 话题之外的东西:
Better create a scope in your
#user.rb:
scope :all_except_current, ->(user) { where.not(id: user) }
#now use this scope in your controller & get all your users except current_uesr
def index
@users = User.all_except_current(current_user)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.