代码之家  ›  专栏  ›  技术社区  ›  Mike Heffner

如何禁用所属对象的默认范围?

  •  39
  • Mike Heffner  · 技术社区  · 17 年前

    有没有办法禁用 default_scope 单身 belongs_to 默认范围 对所有人来说都很好,除了一个人 我想绕过这个范围。我熟悉 with_exclusive_scope 然而,我不认为这可以用来与你属于。

    有什么建议吗?

    branch_source acts_as_revisable 指向不是最新版本的修订( revisable_is_current 是假的)。

    4 回复  |  直到 16 年前
        1
  •  37
  •   lwe    14 年前

    可能有点晚了(短短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
    

    使现代化 :获得基于reflect_on_关联的通用解决方案 https://gist.github.com/2923336

        2
  •  33
  •   John Smith    12 年前
    belongs_to :account, -> { unscope(where: :destroyed_at) }
    

        3
  •  15
  •   Tobias Cohen    15 年前

    我自己也有这个问题,下面是我的想法:

    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
    
        4
  •  0
  •   Zack Xu    7 年前

    belongs_to :document
    

    并将其替换为

    def document
        Document.unscope(where: :deleted_at).find_by(id: document_id)
    end
    
    def document=(d)
        self.document_id = d&.id
    end