我正在将文件存储在 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模型可以将自己与任何"实现"此接口的模型相关联。问题是模型如何以及在哪里:用户和business_listings"实现"这个"消费者"接口。如何设置?
每当要存储有关多对多关系中模型之间关系的属性时,通常关系为 :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
resource_relationship.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
表中具有属性的需求 - 这些属性实际上是consumer
和s3_file
模型的属性,因此最好将它们保留在那里。
:has_many, :through
我通常发现随着模型之间关系的变化而更灵活且更容易修改。