has_many 直通和多态关系
我不知道这是否可能,但这里是:
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的多态关系捕获所有Worm?
看起来有点倒退,但无论如何我都很感谢您的帮助!如果需要任何澄清,尽管询问。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(猜测我自己上面评论的答案)
你不能做你想做的事,没有 Rails 帮助器允许你从
FruitBasket
加入到Worm
中单一协会。您可以拥有apple_worms
和banana_worms
但我确信您已经猜到了,但这不是您想要的。您需要做的是创建自己的方法来获取正确的蠕虫 - 如下所示:
(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
fromFruitBasket
in a single association. You can haveapple_worms
andbanana_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: