Rails STI使用基类查询所有子类

时间:2016-03-25 02:03:20

标签: ruby-on-rails ruby-on-rails-4 single-table-inheritance

想象一下,我将这个STI表称为带有这些子类的生物:

class LivingThing < ActiveRecord::Base
end

class Animal < LivingThing
end

class Plant < LivingThing
end

class Fungus < LivingThing
end

class Cat < Animal
end

class Dog < Animal
end

我试图从子类“Animal”获取INHERIT的所有记录的非常简单的查询。 所以我想要记录类型=“Cat”或type =“Dog”。我不知道为什么我似乎无法解决这个问题。

这些选项都不起作用:

- animals = LivingThing.all.map{|r| r.kind_of?("Animal")}
- animals = LivingThing.all.map{|r| r.type == "Animal"}
- animals = LivingThing.kind_of?("Animal")

目前LivingThing.all =

 => #<ActiveRecord::Relation [#<Cat id: 2,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Dog id: 3,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">,#<Cat id: 4,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Cat id: 5,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Rose id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Oak id: 7,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Mushroom id: 6,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">, #<Ringworm id: 8,  status: 1,  created_at: "2016-03-25 00:57:20", updated_at: "2016-03-25 00:57:20">]> 

2 个答案:

答案 0 :(得分:1)

你可以这样做:

animals = LivingThing.all.map { |r| r if r.class.superclass.name == 'Animal' }

或:

animals = LivingThing.all.map { |r| r if r.class.superclass == Animal }

这应该为您提供从 Animal 类继承的类的所有记录。

答案 1 :(得分:0)

从rails 4.2开始(甚至可能在之前),做:

Animal.all将自动呈现类似于:

的SQL调用

SELECT * FROM "living_things" WHERE "living_things"."type" IN ('Animal', 'Dog', 'Cat')

所以你有它。 : - )