如何使用单个表在模型和其他几个模型之间设置HABTM关系?

时间:2013-07-20 18:08:27

标签: ruby-on-rails ruby-on-rails-3 polymorphism associations has-and-belongs-to-many

对于以下情况,我很难理解必要的关联:

  • 我有一个“上传”,可以附加到“人”,a “团体”,“项目”或“办公室”。

  • 上传需要同时属于多个人,群组或项目(即:可以链接到两个人,三个项目,一个群组,两个办事处。 )

  • 个人,项目,群组或项目可以有多个与他们相关联的上传。

  • 我希望能够获取与对象关联的所有上传(例如:@ project.uploads),以及上传链接到的所有项目(在单个方法中,例如@ upload.linked_to)

我正在努力避免为每个可能的关联(projects_uploads,people_uploads,offices_uploads)创建一个表,因为我希望它更灵活,因为可能有其他模型我希望将来链接上传。

多态关联可能是我需要的......但我还没有找到一个与我想要完成的事情非常相似的例子。

有人能指出我正确的方向吗?

谢谢!如有必要,我可以尝试澄清我的问题:)

修改 解决了!这就是我最终设置它的方式:


模型

Upload.rb

class Upload < ActiveRecord::Base

  has_many :upload_connections

  def linked # Shortcut for @upload.upload_connections
    self.upload_connections
  end

end

Upload_connection.rb

class UploadConnection < ActiveRecord::Base

  belongs_to :uploadable, :polymorphic => true
  belongs_to :upload

end

Project.rb / Office.rb / Person.rb等

class Project < ActiveRecord::Base 
# (same for project, office, person, etc.)

  has_many :upload_connections, :as => :uploadable
  has_many :uploads, :through => :upload_connections

end

表格结构

上传

id: integer
filename: string
description: string

Upload_connections

id: integer
uploadable_id: integer
uploadable_type: string
upload_id: integer

...加上要与之关联的对象的表格。

1 个答案:

答案 0 :(得分:1)

多态关联就是你想要的。我不认为你想要每个关联单独的表。这只会变得混乱。

class Upload << AR
  has_many :links
  has_many :users, :through => :links, :conditions => {:mediable_type => 'User'}
end

class Link << AR
  belongs_to :upload
  belongs_to :linkable, :polymorphic => true
end

class User << AR # and Project, Group, and Office
  has_many :links, :as => :linkable
  has_many :uploads, :through => :links
end

FWIW,“Link”是一个可怕的名字,但我现在想不出更好的东西。我的一些语法可能会关闭,但应该足够接近让你离开。