Rails Associations,habtm?多态?都?

phi*_*ash 5 polymorphism ruby-on-rails has-and-belongs-to-many

在我的Rails应用程序中,我有三个模型,Projects,BlogPosts和Images.Projects和BlogPosts可以有许多链接的图像,图像可以链接到Project,BlogPost或两者.

在Rails中设置关联以使其工作的最佳方法是什么?

Mic*_*are 9

我将这个问题梳理成一个单独的模型类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
Run Code Online (Sandbox Code Playgroud)

  • 这并不是一个"戏弄"的习惯,因为它实际上与habtm相同(使用ImageLink作为habtm表),但这种方法的优点是你将两个habtms合二为一. (2认同)
  • 谢谢,我添加了has_many:通过关联到这一点,在过程中发现从图像方面不起作用,但在这种情况下无关紧要因为我只想将图像链接到Projects而不是反过来说. (2认同)