Nice programing

Rails ActiveRecord : 현재 사용자를 제외한 모든 사용자 찾기

nicepro 2020. 12. 13. 11:06
반응형

Rails ActiveRecord : 현재 사용자를 제외한 모든 사용자 찾기


나는 이것이 매우 간단해야한다고 생각하지만 내 두뇌는 그것에 대해 단락되어 있습니다. 현재 사용자를 나타내는 개체가 있고 현재 사용자를 제외한 모든 사용자를 쿼리하려는 경우 현재 사용자가 때때로있을 수 있다는 점을 고려하여 어떻게 할 수 nil있습니까?

이것이 내가 지금하고있는 일입니다.

def index
  @users = User.all
  @users.delete current_user
end

내가 싫어하는 것은 쿼리 결과에 대한 후 처리를하고 있다는 것입니다. 약간의 오해를 느끼는 것 외에도 .NET으로 실행되도록 쿼리를 변환하면 제대로 작동하지 않을 것이라고 생각합니다 will_paginate. 쿼리로이를 수행하는 방법에 대한 제안 사항이 있습니까? 감사.


Rails 4에서는 다음을 수행 할 수 있습니다.

User.where.not(id: id)

멋진 범위로 포장 할 수 있습니다.

scope :all_except, ->(user) { where.not(id: user) }
@users = User.all_except(current_user)

또는 원하는 경우 클래스 메서드를 사용하십시오.

def self.all_except(user)
  where.not(id: user)
end

두 방법 모두 AR 관계 객체를 반환합니다. 즉, 메서드 호출을 연결할 수 있습니다.

@users = User.all_except(current_user).paginate

where()배열도 허용 하므로 사용자 수에 관계없이 제외 할 수 있습니다 .

@users = User.all_except([1,2,3])

예를 들면 :

@users = User.all_except(User.unverified)

그리고 다른 협회를 통해서도 :

class Post < ActiveRecord::Base
  has_many :comments
  has_many :commenters, -> { uniq }, through: :comments
end

@commenters = @post.commenters.all_except(@post.author)

참조 where.not()에서 API 문서 도구 .


@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))

예를 들어 모델에서 named_scope를 만들 수도 있습니다.

named_scope :without_user, lambda{|user| user ? {:conditions => ["id != ?", user.id]} : {} }

컨트롤러에서 :

def index
  @users = User.without_user(current_user).paginate
end

이 범위는 nil로 호출 될 때 모든 사용자를 반환하고 다른 경우에는 param에 제공된 것을 제외한 모든 사용자를 반환합니다. 이 솔루션의 장점은이 호출을 다른 명명 된 범위 또는 will_paginate paginate 메서드와 자유롭게 연결할 수 있다는 것입니다.


다음은 더 짧은 버전입니다.

User.all :conditions => (current_user ? ["id != ?", current_user.id] : [])

GhandaL의 답변에 대한 한 가지 참고 사항-적어도 Rails 3에서는 수정할 가치가 있습니다.

scope :without_user, lambda{|user| user ? {:conditions => ["users.id != ?", user.id]} : {} }

(여기서 주요 변경 사항은 'id! = ...'에서 'users.id! = ...'로, 또한 Rails 3의 named_scope 대신 범위입니다)

원래 버전은 단순히 Users 테이블의 범위를 지정할 때 잘 작동합니다. 연관에 범위를 적용 할 때 (예 : team.members.without_user (current_user) ....),이 변경은 ID 비교에 사용중인 테이블을 명확히하기 위해 필요했습니다. 나는 그것없이 SQL 오류 (SQLite 사용)를 보았다.

별도의 답변에 대한 사과 ... 아직 GhandaL의 답변에 대해 직접 언급 할 평판이 없습니다.


내가 사용한 아주 쉬운 솔루션

@users = User.all.where("id != ?", current_user.id)

User.all.where ( "id NOT IN (?)", current_user.id)는 예외 정의되지 않은 메서드를 통해 #<Array:0x0000000aef08f8>

User.where("id NOT IN (?)", current_user.id)

할 수있는 또 다른 쉬운 방법 :

@users = User.all.where("id NOT IN(?)", current_user.id)

배열이 더 도움이 될 것입니다

arrayID [0] = 1

arrayID [1] = 3

User.where.not (id : arrayID)


User.where (: id.ne => current_user.id)


What you are doing is deleting the current_user from the @users Array. This won't work since there isn't a delete method for arrays. What you probably want to do is this

def index
  @users = User.all
  @users - [current_user]
end

This will return a copy of the @users array, but with the current_user object removed (it it was contained in the array in the first place.

Note: This may not work if array subtraction is based on exact matches of objects and not the content. But it worked with strings when I tried it. Remember to enclose current_user in [] to force it into an Array.

참고URL : https://stackoverflow.com/questions/2672744/rails-activerecord-find-all-users-except-current-user

반응형