简体   繁体   English

在Rails中通过关联模型的子类进行查询

[英]Query by an associated model's subclass in rails

I have used Single Table Inheritance (STI) to create some Models with subclassed from a common parent. 我已经使用单表继承(STI)来创建一些模型,这些模型具有从公共父级继承来的子类。 A separate model has an association with the superclass. 单独的模型与超类具有关联。 Eg: as follows... 例如:如下...

class Fruit < ActiveRecord::Base
  has_many :smoothies
end

class Apple < Fruit
end

class Banana < Fruit
end

class Smoothie < ActiveRecord::Base
  belongs_to :fruit
end

Is there any way to query for a certain subclass without manually creating a method for each subclass? 有什么方法可以查询某个子类,而无需为每个子类手动创建方法?

I would like to be able to do something along the lines of my_smoothie.apple to get an Apple instance if my_smoothie is associated with an Apple 如果my_smoothieApple关联,我希望能够执行类似于my_smoothie.apple来获取Apple实例。

Update 更新资料

My use case is actually where I have a relation of Smoothies and I want to do some_smoothies.apples to get a relation containing any associated Apples. 我的用例实际上是我有一个冰沙关系,并且我想做some_smoothies.apples以获得包含任何关联的Apple的关系。

If you do a my_smoothie.fruit, you should get back an Apple object (not a Fruit object, Rails magic). 如果执行my_smoothie.fruit,则应取回Apple对象(而不是Fruit对象,Rails魔术)。 You may be good as is. 您可能会很好。

could you do this? 你能做到吗?

my_smoothie.fruit.where(type: "Apple")

Of course if you need to dynamically infer the name of your subclasses you could use 当然,如果您需要动态推断子类的名称,则可以使用

subclass_object.class.to_s # if you have an instantiated object e.g. of 'apple'
subclass.to_s # if you start form the subclass e.g. of Apple

And if this is ok for you, consider creating named scopes for it 如果可以,请考虑为其创建命名范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM