2012-10-16 2 views
4

Location이라는 클래스가 있습니다. 단일 쿼리 내에서 직접적인 모든 자식을 미리로드하고 싶습니다. Location 클래스와 관련finder_sql에 의해 관계가 정의 될 때 열의 적재 관계 - finder_sql을 무시하고 기본 has_many 질의를 생성

는 다음과 같이 정의한다 :

has_many :children, 
    class_name: self, 
    finder_sql: ->(query) { 
     self.class.where(%Q{"locations"."ancestry" like '%#{id}'}).to_sql 
    }, 
    counter_sql: ->(query) { 
    self.class.where(%Q{"locations"."ancestry" like '%#{id}'}).count.to_sql 
    } 


Location.first.children 
    Location Load (0.4ms) SELECT "locations".* FROM "locations" LIMIT 1 
    Location Load (0.3ms) SELECT "locations".* FROM "locations" WHERE ("locations"."ancestry" like '%1') 
    => [#<Location id: 2, code: nil, name: "Niger 1349875728.873964", alternative_name: nil, ancestry: "1", coordinates: nil, ancestry_depth: 1>, (...)] 

하지만이를 최적화하고 두 일괄 적으로 모두를로드 할 때

Location.includes(:children).where(id: [5, 100]).all 
    Location Load (0.4ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" IN (5, 100) 
    Location Load (0.2ms) SELECT "locations".* FROM "locations" WHERE "locations"."location_id" IN ('5') 
    ActiveRecord::StatementInvalid: PG::Error: ERROR: column locations.location_id does not exist 
    LINE 1: SELECT "locations".* FROM "locations" WHERE "locations"."lo... 
               ^
    : SELECT "locations".* FROM "locations" WHERE "locations"."location_id" IN ('5') 
    from /xxx/.rvm/gems/[email protected]/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1158:in `async_exec' 

레일 버그이에게, 아니면해야 나는 그것을 다른 방식으로 정의합니까?

관계에 대한 find_in_collection을 덮어 쓰려고하는데 영향이 없습니다.

답변

0

네, 레일즈와 너무 싸우고 있습니다. has_many에 조건 PARAM를 사용

has_many :children, class_name: self, conditions: [%Q{"locations"."ancestry" like '%#{id}'}] 

또한 그냥 등의 사용에 대해 궁금? 왜 =에 대한 테스트를하지 않습니까?

has_many :children, class_name: self, foreign_key: :ancester_id 
: 당신이 경로를 이동하는 경우 문체 _id가 있어야 또한

has_many :children, class_name: self, foreign_key: :ancestry 

,