2017-11-08 5 views
0

계정이 있고 사용자 계정이 has_one 인 사용자 모델이 있습니다. 그래서 내 사용자 테이블에 account_id가 있습니다.계정에 사용자가있는 레일스 범위

나는 has_user = TUE/FALSE를 전달할 수있는 계정에 대한 범위를 만들고 사용자가 있거나없는 계정을 반환합니다.

scope :has_user, -> (has_user) { where(...) } 

누구든지이 범위를 작성하는 방법을 도울 수 있습니까?

class Account < ApplicationRecord 
    has_one :user 

    scope :has_user, -> { includes(:user).where.not(users: { account_id: nil }) } 
    scope :has_not_user, -> { includes(:user).where(users: { account_id: nil }) } 
end 

다른 방법 :

답변

0

나는 당신이 반대를위한 관련 및 기타 사용자와 계정에 대해 당신이 인수를 전달하지 않도록 이런 식으로 물어, 하나를이 개 범위를 만들 수와 같은 wherewhere.not를 사용할 수 있다고 생각

def self.has_user(condition) 
    if condition 
    includes(:user).where.not(users: { account_id: nil }) 
    else 
    includes(:user).where(users: { account_id: nil }) 
    end 
end 

호기심 아웃 : 어디 및/또는 where.not 확인하는 부울 값과 if 문을 사용을 허용하는 클래스 메소드를 만들 수

,
def self.has_user(bool) 
    hash = { users: { account_id: nil } } 
    query = ->(assoc) { bool ? assoc.where.not(hash) : assoc.where(hash) } 
    query.(includes :user) 
end 
0

당신 조인을 사용하여보다 효율적인 쿼리를 작성할 수있는 원시 SQL을 사용하지만이 작동합니다 : 계정 has_one 사용자 내가 다음 계정 belongs_to 그 사용자를 가정하면 사용자 테이블에 ACCOUNT_ID이

scope :has_user, -> (has_user) { 
    account_ids = User.where.not(account_id: nil).pluck(:account_id) 
    has_user ? where(id: account_ids) ? where.not(id: account_ids) 
} 

경우 .

0

다른 방법이 될 것입니다,

class Account < ApplicationRecord 
    has_one :user 

    scope :has_user, ->(has_user = true) { 
    criteria = (has_user == true ? 'IN' : 'NOT IN') 
    where("id #{criteria} (SELECT DISTINCT(account_id) FROM users)") 
    } 
end 

기본값 사실이 has_user 변수에 할당

Account.has_user # Accounts with user

Account.has_user(false) # Accounts without user