如何确定模型上的所有查询范围

时间:2014-12-12 10:11:36

标签: ruby-on-rails

我正在使用rails 3.1.10上的spree。

我希望确定模型Variants上的所有查询的范围,以便仅返回带有deleted_at列的变体。我想将这个条件放在所有问题上,例如find_by_%where等。

我怎样才能做到这一点?狂欢核心中的变体类已经具有以下内容:

include ::Scopes::Variant
  # default variant scope only lists non-deleted variants
  scope :active, where("variants.deleted_at is null")
  scope :deleted, where("not variants.deleted_at is null")

不确定为什么控制台中的查询不符合此范围

那么,1。我如何确定所有查询的范围     2.为什么spree-core中的默认范围没有被应用,我是否还需要在我的装饰器中包含它?

2 个答案:

答案 0 :(得分:0)

For 1 - 使用default_scope模型来确定所有查询的范围

default_scope where("variants.deleted_at is null")

答案 1 :(得分:-1)

您需要使用default_scope。 我的建议: 你需要创建子模型

class A < ActiveRecord::Base
end

class AWithDeletedIsNull(or another) < A
  default_scope where("variants.deleted_at is null")
end

class AWithDeletedIsNotNull(or another) < A
  default_scope where("not variants.deleted_at is null")
end

使用:

VariantWithDeletedIsNull.find(1)