简体   繁体   English

Rails Associations,habtm? 多态? 都?

[英]Rails Associations, habtm? Polymorphic? Both?

In my Rails app I have three models, Projects, BlogPosts and Images. 在我的Rails应用程序中,我有三个模型,Projects,BlogPosts和Images。 Projects and BlogPosts can have many linked images and an image can be linked to a Project, a BlogPost or both. Projects和BlogPosts可以有许多链接的图像,图像可以链接到Project,BlogPost或两者。

What is the best way of setting up the associations to make this work in Rails? 在Rails中设置关联以使其工作的最佳方法是什么?

I'd tease out the habtm into a separate model class, ImageLink. 我将这个问题梳理成一个单独的模型类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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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