[英]Query by an associated model's subclass in rails
我已經使用單表繼承(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
與Apple
關聯,我希望能夠執行類似於my_smoothie.apple
來獲取Apple
實例。
更新資料
我的用例實際上是我有一個冰沙關系,並且我想做some_smoothies.apples
以獲得包含任何關聯的Apple的關系。
如果執行my_smoothie.fruit,則應取回Apple對象(而不是Fruit對象,Rails魔術)。 您可能會很好。
你能做到嗎?
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
如果可以,請考慮為其創建命名范圍
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.