繁体   English   中英

如何在has_many的中间模型中创建has_many关联:以最佳方式通过关联Rails

[英]How to create has_many associations in the intermediate model of has_many :through association in an optimal way Rails

我想要的是一个可以在其中创建内容的配置文件,每个内容可以包含许多视频,许多图像等等。 这就是为什么我将视频和图像视为不同的表格。 但我想知道视频是否属于特定的个人资料或内容,而无需编写复杂的查询。

我有以下具有has_many的模型:通过关联

class Profile < ApplicationRecord
  has_many :contents
  has_many :videos, through: :contents
end

class Content < ApplicationRecord
  belongs_to :profile
  belongs_to :video
end

class Video < ApplicationRecord
  has_many :contents
  has_many :profiles, through: :contents
end

和以下迁移

create_table :contents do |t|
  t.string :name
  t.text :description
  t.references :video, foreign_key: true
  t.references :profile, foreign_key: true
end

create_table :profiles do |t|
  t.integer :profile_type
  t.references :user, foreign_key: true
end

create_table :videos do |t|
  t.string :name
  t.string :file
  t.string :link
end

到目前为止,我的问题是每个内容只能有一个视频。 如何在Content(中间表)中存储许多视频,以通过关联保持has_many?

由于我想拥有不同种类的内容,这意味着它们将是多余的表,并且我想获得一些想法来帮助我改进这种方法

注意:我正在阅读本文档, http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

您之间存在“真实性”冲突

我可以在其中创建内容的配置文件,每个内容可以包含许多视频,许多图像等

和您实际的代码实现是:

  • 您声明要:
    • 个人资料有很多内容
    • 内容有很多视频
  • ...但是您的代码是:
    • 个人资料有很多内容
    • 视频内容很多

因此,如果我理解正确,并假设您要将“代码”更改为“想要”,则:

TL; DR:

class Profile < ApplicationRecord
  has_many :contents
  has_many :videos, through: :contents
end

class Content < ApplicationRecord
  belongs_to :profile
  has_many :videos
end

class Video < ApplicationRecord
  belongs_to :content
end

您的架构应如下所示:

create_table :contents do |t|
  t.string :name
  t.text :description
  t.references :profile, foreign_key: true
end

create_table :profiles do |t|
  t.integer :profile_type
  t.references :user, foreign_key: true
end

create_table :videos do |t|
  t.string :name
  t.string :file
  t.string :link
  t.references :content, foreign_key: true
end
  • 上面的代码应回答您的其他问题:

    如何在内容中存储许多视频

    ...因为内容记录现在有很多视频

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM