0

我将文件存储在 Amazon s3 上。每个文件都有许多“消费者”,这些消费者可以是任何类型(用户、外部应用程序、business_listings 等)。这需要多对多的关系。但是,我还想存储有关每个关系的某些属性。所以我认为解决这个问题的最好方法是在“s3_files”消费者之间创建一个 *has_and_belngs_to_many_through* 关系

现在的问题是,既然有很多类型的消费者,我需要使用多态关联。

因此,基于此,我将采取以下步骤:

1) Create a model: "resource_relationship"
2) Have these fields in it:
  t.string: consumer_type
  t.string: s3_fileType
  t.string: file_path
  t.string: consumer_type
  t.integer: s3_file.id
  t.integer: consumer.id
  t.integer: resource_relationship.id
 3) Add to the model:
     belongs_to: s3_file
     belongs_to: consumer
 4) add_index:[s3_file.id, consumer.id]

 5) Inside: s3_file
     nas_many: resource_relationships
     has_many:consumers :through=> :resource_relationships
 6) Inside: Users
     nas_many: resource_relationships
     has_many:s3_files :through=> :resource_relationships
 7) Inside: business_listings
     nas_many: resource_relationships
     has_many:s3_files :through=> :resource_relationships

我的困惑在于这种关系的多态部分。

因为我没有“消费者”模型。我不明白这如何适合这个等式。我在网上看到了一些教程并提出了上述方法和概念,但是,我不确定这是否是解决此问题的正确方法。

本质上,我在这里理解“消费者”就像所有模型“实现”的接口,然后 S3_file 模型可以将自己与任何“实现”此接口的模型相关联。问题是模型如何以及在哪里做的:用户和业务列表“实现”这个“消费者”接口。我该如何设置?

4

1 回答 1

1

每当您想在多对多关系中存储有关模型之间关系的属性时,通常关系是:has_many, :through

我建议从这种更简单的方法开始,然后在需要时考虑多态性。现在,从拥有一个consumer_type可以在需要时使用的属性开始。

消费者.rb:

class Consumer < ActiveRecord::Base
  has_many :resource_relationships
  has_many :s3_files, through: :resource_relationships
  validates_presence_of :consumer_type
end

资源关系.rb:

class ResourceRelationship < ActiveRecord::Base
  belongs_to :consumer
  belongs_to :s3_file
end

s3_file.rb

class S3File < ActiveRecord::Base
  has_many :resource_relationships
  has_many :consumers, through: :resource_relationships
  validates_presence_of :s3_fileType
  validates_presence_of :file_path
end

请注意,这也简化了在resource_relationships表中包含属性的需求——这些属性实际上是consumers3_file模型的属性,因此最好将它们保留在那里。

:has_many, :through随着模型之间的关系发生变化,我通常会发现它更灵活、更容易修改。

于 2012-07-06T03:52:03.700 回答