在rails中查询关联模型的子类

时间:2013-01-09 20:14:32

标签: ruby-on-rails associations rails-activerecord sti

我使用单表继承(STI)来创建一些带有子公共父类的模型。单独的模型与超类有关联。例如:如下......

class Fruit < ActiveRecord::Base
  has_many :smoothies
end

class Apple < Fruit
end

class Banana < Fruit
end

class Smoothie < ActiveRecord::Base
  belongs_to :fruit
end

有没有办法在不为每个子类手动创建方法的情况下查询某个子类?

如果my_smoothie.appleApple

相关联,我希望能够按my_smoothie的方式执行Apple个实例。

更新

我的用例实际上是我与Smoothies的关系,我想some_smoothies.apples来获取包含任何相关苹果的关系。

2 个答案:

答案 0 :(得分:0)

如果你做了my_smoothie.fruit,你应该找回一个Apple对象(不是Fruit对象,Rails魔法)。你可能会很好。

答案 1 :(得分:0)

你可以这样做吗?

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

当然,如果您需要动态推断子类的名称,可以使用

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

如果你没问题,可以考虑为它创建named scopes

相关问题