Person 在哪里而不是 Person::Single

Where is Person and not Person::Single

假设我有三个 类

Person

Person::Single < Person

Person::Married < Person

假设我有 两个 单身人士 => Person::Single

然后我得到两个人:

Person.all.count
=> 2

但我的目标是只获得 Person 类型的人,而不是 Person::SinglePerson::Married

类型的人

我试过的是:

Person.where(type: Person.to_s)
=> 2

但这也是 returns 2 因为 Person::SinglePerson::Married 继承自 Person

我可以做什么? 例如,有没有一种方法可以说 ::Single::Married 具有与 person 相同的方法但不是同一类型?谢谢

因为它标有 rails 标签,我假设你的 Person class 是一个 ActiveRecord 模型。缺少更多信息,但我只是假设我真的不知道 ;)

Your Person class 继承 ActiveRecord 方法,例如 "all" 和 Person::Single (和 ::Maried)将通过 Person.

继承它

所以,自然地,当你执行 Person.all 时,它只会执行常规的 <#ActiveRecord>.all 方法,它不知道也不关心: :单身和::已婚。

您可以做的是根据您调用的 class 名称动态设置 default_scope .all、.where 或其他名称。

class Person < ActiveRecord::Base
  ...

  def self.default_scope
    scope = if self.name == Person.sti_name
      where(:type => Person.sti_name)
    else
      nil
    end

    scope
  end
 end

这还将确定您的 where(:whatever => x) 查询的范围。

但是,这是假设您的 Person 模型(数据库中的列)有一个名为 "type" 的属性。

编辑: 正如 Holger 所指出的,rails STI 已经包含了魔法。我仍然认为设置默认范围是可行的,只是你应该跳过设置单身和已婚的范围。 如果你不需要它作为默认范围,你应该尝试 Person.where(:type => Person.sti_name)Person.where(:type => Person.name) 因为 rails 将 class 名称断言为 sti_name 如果 class 继承自 ActiveRecord::Base.

试试这个:

Person.where(:type => Person).count