I don't know if this is possible, but here goes:
FruitBasket
has_many :apples
has_many :bananas
######## What to put here to access Worm through its pest_holder relationship?
Apple
has_many :worms, :as => :pest_holder
belongs_to :fruit_basket
Banana
has_many :worms, :as => :pest_holder
belongs_to :fruit_basket
Worm
belongs_to :pest_holder, :polymorphic => true
What is the开发者_StackOverflow社区 relationship I need to be able to call:
red_delicious = Apple.first
red_delicious.worms.whatever
And have it grab all of the Worm's through Apple's and Banana's polymorphic relationship with Worm?
It seems kind of backwards, but I appreciate the help anyway! If there's any clarification needed, just ask.
(Guessing the answer to my own comment above)
You can't do what you want to, there's no Rails helper to allow you to join through to Worm
from FruitBasket
in a single association. You can have apple_worms
and banana_worms
but I'm sure you guessed that already, and that that's not what you want.
What you'll need to do is to create your own method to get to the correct Worm
s - something like this:
def worms
Worm.where :id => apple_ids + banana_ids
end
精彩评论