简体   繁体   中英

has_many through and polymorphic relationships

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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