2012-12-13 1 views
2

글 머리 기호를 사용하여 N + 1 쿼리를 알려줍니다.항상 열심히로드하는 모델을 포함하는 방법

나는 include sporadically를 추가하지 않으려합니다.

나는 언제든지 코멘트 모델뿐만 아니라 사용자를 포함하는 액세스되는 모델을 말할 수있는 방법이있는 user 모델

에 속하는 comment 모델을 가지고? (대신 Comment.include(:user) 매번 일을)

답변

6

당신은 default_scope를 사용할 수 있습니다

class Comment < ActiveRecord::Base 
    default_scope includes(:user) 
end 

Comment.first # => the same as Comment.includes(:user).first 
+0

감사해야, 어떻게 사용합니까 그 default_scope'로 : 순서 => 'DESC created_at' '? –

+1

'default_scope includes (: user) .order ("created_at desc")'를 시도하십시오. – kulesa

1

당신은

class Comment < ActiveRecord::Base 
    default_scope { includes(:user) } 
end