has_many 直通和多态关系

发布于 2024-11-14 09:57:26 字数 582 浏览 2 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我闹别瞎闹 2024-11-21 09:57:26

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

你不能做你想做的事,没有 Rails 帮助器允许你从 FruitBasket 加入到 Worm 中单一协会。您可以拥有 apple_wormsbanana_worms 但我确信您已经猜到了,但这不是您想要的。

您需要做的是创建自己的方法来获取正确的蠕虫 - 如下所示:

def worms
  Worm.where :id => apple_ids + banana_ids
end

(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 Worms - something like this:

def worms
  Worm.where :id => apple_ids + banana_ids
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文