has_many通过和多态关系

时间:2011-06-08 19:06:29

标签: ruby-on-rails ruby-on-rails-3 has-many has-many-through has-many-polymorphs

我不知道这是否可行,但这里有:

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

我需要能够打电话的关系是什么:

red_delicious = Apple.first
red_delicious.worms.whatever

让它通过Apple和Banana与Worm的多态关系获取所有蠕虫?

看起来有些倒退,但无论如何我还是很感激!如果需要澄清,请询问。

1 个答案:

答案 0 :(得分:1)

(猜测上面我自己评论的答案)

你不能做你想做的事情,没有Rails助手允许你在一个关联中从Worm加入FruitBasket。你可以拥有apple_wormsbanana_worms,但我确定你已经猜到了,那不是你想要的。

您需要做的是创建自己的方法以获得正确的Worm - 类似这样的内容:

def worms
  Worm.where :id => apple_ids + banana_ids
end
相关问题