铁路协会,habtm? 多态性? 两个都?

发布于 2024-07-08 10:45:21 字数 120 浏览 6 评论 0原文

在我的 Rails 应用程序中,我有三个模型:项目、博客帖子和图像。 项目和博客文章可以有许多链接的图像,并且图像可以链接到项目、博客文章或两者。

建立关联以使其在 Rails 中工作的最佳方式是什么?

In my Rails app I have three models, Projects, BlogPosts and Images. Projects and BlogPosts can have many linked images and an image can be linked to a Project, a BlogPost or both.

What is the best way of setting up the associations to make this work in Rails?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

野鹿林 2024-07-15 10:45:21

我会将 habtm 梳理成一个单独的模型类 ImageLink。 然后你会得到:

Project
  has_many :image_links, :as => :resource
BlogPost
  has_many :image_links, :as => :resource
ImageLink
  belongs_to :image
  belongs_to :resource, :polymorphic => true
Image:
  has_many :image_links

I'd tease out the habtm into a separate model class, ImageLink. Then you'd get:

Project
  has_many :image_links, :as => :resource
BlogPost
  has_many :image_links, :as => :resource
ImageLink
  belongs_to :image
  belongs_to :resource, :polymorphic => true
Image:
  has_many :image_links
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文