Rails协会 - 最佳实践的想法

Gal*_*axy 5 activerecord ruby-on-rails ruby-on-rails-3

关于Rails关联的问题.
考虑以下模型:


  • 活动
  • 图片

人和事件可以有很多图像.
上传到活动的图片需要能够与多个人相关联.

这意味着图像之间存在两种关系.
将图像直接上传到此人的图像.还有一个人在活动中被贴上标签.

根据事件中一个(或多个)图像标记的事实,事件之间是否存在关系?在这方面,它是一种图像标记系统,其中基于人们被标记的事件来创建关联.

想知道Rails创建这种关联的最佳做法是什么?非常感谢任何帮助或建议!

nat*_*vda 2

在rails中,绝对可以定义一个具有额外字段的连接表。因此,在这种情况下,我将定义下表:

class LinkedImage
  belongs_to :person
  belongs_to :image

  OWNER=1
  TAGGED=2

  validates :relation_type, :inclusion => {:in => [OWNER, TAGGED]}
end
Run Code Online (Sandbox Code Playgroud)

该表将图像链接到一个人,并且有一个额外的字段relation_type(您可能会想到一个更合适的名称),它现在可以有两个值:1(对于OWNER,意味着图像直接上传到该人),和 2(该人在图像中被标记)。除了关系之外,也许您想存储一些额外的东西,例如图像中的位置、额外的注释,那么您也可以轻松地在此处添加它们。

这个人看起来像:

class Person
  has_many :linked_images
  has_many :uploaded_images, :class_name => Image, 
                             :through => :linked_images, 
                             :conditions => "relation_type=#{LinkedImage::OWNER}"
  has_many :tagged_in_images, :class_name => Image,
                              :through => :linked_images,
                              :conditions => 'relation_type=#{LinkedImage::TAGGED}"
end 
Run Code Online (Sandbox Code Playgroud)

的代码Image可能类似。

我希望这有帮助。