Rails Associations,habtm?多态?都?
-
05-07-2019 - |
题
在我的Rails应用程序中,我有三个模型,Projects,BlogPosts和Images。 Projects和BlogPosts可以有很多链接的图像,图像可以链接到Project,BlogPost或两者。
设置关联以使其在Rails中工作的最佳方法是什么?
解决方案
我将这个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
不隶属于 StackOverflow