2014-09-08 5 views
0

레일 3.2를 사용하고 있습니다. 나는 다음과 같은 설정을 가지고 :레일에있는 모델을 사용하여 쿼리하는 방법

단지 다음과 같이, 액티브 쿼리를 사용하지 않을 경우이 작동
class User < ActiveRecord::Base 
    attr_accessible :is_admin 
    belongs_to :created_by, :foreign_key => :created_by_id, :class_name => 'User' 
end 

: 난 정말 어떤 도움을 감사하게 될 것입니다

#rails console 
User.first.created_by.is_admin 
#=> true 

#But I want to query like the following, but it doesn't work 
User.where(:created_by => {:is_admin => true}) 
#ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'created_by.is_admin' in 'where clause'... 

#This also doesn't work: 
User.joins(:created_by).where(:created_by => {:is_admin => true}) 
#ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'created_by.is_admin' in 'where clause' 

.

+0

'User.includes (: created_by) .where (: created_by => {: is_admin => true})' –

+0

'join '대신'include'도 작동하지 않았습니다 –

답변

1

당신은이 쿼리

admin_ids = User.where(:is_admin => true).pluck(:id) 
@users = User.where(:created_by_id => admin_ids) 

시간의

  • 많은, 2 개 간단한 쿼리 빨리 1 복잡한보다 쿼리를
  • 읽을 수 &에 가입하기 때문에이 작업을 수행 할 것을 사용하여 그것을 할 수 알기 쉬운 것
+0

고맙습니다. 불행히도, 내 코드에서 중첩 된 쿼리이기 때문에 하나의 쿼리로 정말 필요했습니다. Like : users = ... \ n users = users.where (...) 그러나 정말로 간단한 방법이 없다면, 당신이 제안한 것과 같은 어려운 방법을 수행 할 것입니다. –

+0

오 기다려. 중첩 된 쿼리를 사용하는 경우에도 여전히 두 개의 쿼리를 수행 할 수 있다고 생각합니다 ... 감사합니다. 작동하는지 확인해 보겠습니다. –

+0

'admin_ids'는 별도의 쿼리입니다. '(created_by_id => admin_ids)'는 어디에서 연결될 수 있습니까 – Santhosh

관련 문제