2009-10-08 6 views
36

belongs_to에 대해 default_scope을 사용하지 않도록 설정하는 방법이 있습니까? default_scope은 범위를 우회하고 싶은 모든 것을 제외하고는 하나 뿐인 belongs_to을 사용하는 것이 좋습니다. 나는 with_exclusive_scope에 익숙하지만 belongs_to와 함께 사용할 수 있다고는 생각하지 않습니다.belongs_to에 default_scope를 사용하지 않도록 설정하는 방법은 무엇입니까?

제안 사항?

컨텍스트 : 연관에서 acts_as_revisable이 최신이 아닌 수정 버전 (예 : revisable_is_current이 false)을 가리킬 수 있도록하려고합니다.

답변

14

그냥이 문제를 자신을했고, 여기에 내가 생각 해낸 무엇 : 아마

class Comment < ActiveRecord::Base 
    belongs_to :document # Document has some kind of default scope 
         # that stops us from finding it 

    # Override getter method for document association 
    def document_with_unscoped 
    # Fetch document with default scope disabled 
    Document.unscoped { document_without_unscoped } 
    end 
    alias_method_chain :document, :unscoped 
end 
31

(3 년의 단지 짧은) 파티에 조금 늦게, 그러나 다만 같은 문제와 솔루션으로 실행 Tobias의 올바른 방향은 분명하지만 Rails 3.2 이상에서는 간단해질 수 있습니다.

class Comment < ActiveRecord::Base 
    # Document has some kind of default_scope 
    belongs_to :document 

    # Ensure document is not scoped, because Rails 3.2 uses modules it's 
    # possible to use simple inheritance. 
    def document 
    Document.unscoped { super } 
    end 
end 
: 난 아직도 좋아하지 않는 유일한 것은

는 어쨌든 이것이 내가 가지고 올 한 것입니다 ... 어쩌면 반사를 사용하여 활용하는 것이 가능, 문서의 "하드 코딩"클래스 이름입니다

업데이트는 : 나를 위해 작품 https://gist.github.com/2923336

25
belongs_to :account, -> { unscope(where: :destroyed_at) } 

은 4.1

+1

레일이 할 수 reflect_on_association을 기반으로, 일반적인 솔루션을 가지고 모든 조건을 밝혀 내지 못했습니까? – freemanoid

+0

레일 4.1+를위한 훌륭한 솔루션, 감사합니다! – ryancheung

+0

기본 범위가 문자열/sql 형식 인 경우 작동하지 않습니다 –

관련 문제