开发者

How to return children objects?

开发者 https://www.devze.com 2022-12-26 08:29 出处:网络
I have -- what I think -- is a simple question.Here\'s my code: class开发者_如何转开发 Fruit < ActiveRecord::Base

I have -- what I think -- is a simple question. Here's my code:

class开发者_如何转开发 Fruit < ActiveRecord::Base
end

class Apple < Fruit
end

class Kiwi < Fruit
end

Assume that I have all the STI setup correctly, and there are multiple types of Apple and Kiwi records in the table. From here...

fruits = Fruit.find(:all)

...how do I return an array of just Apples from the fruits array?


The same way you would do it if they were just normal objects:

fruits.select {|fruit| fruit.is_a?(Apple) }

STI uses the type field to keep track of the submodel, so you could also do

fruits.select {|fruit| fruit.type == "Apple" }

If you want to get only the apples from the database, just do

Apple.find(:all)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号