【发布时间】:2016-06-30 15:17:36
【问题描述】:
我在这里阅读了很多关于连接表、STI 表和多态关联的问题和答案,此外还有许多遍布互联网的文章和文档。虽然我学到了很多东西,但我仍然对在我的情况下应该做什么感到困惑。我可能已经阅读了答案,但不知道我正在阅读答案,但我想看看是否有人可以帮助我了解我应该在这里做什么。
我有一个 Gallery 模型、一个 Album 模型、一个 Image 模型和一个 Category 模型。这些都嵌套在 User 模型中。
当您创建专辑时,为其分配一个类别,这些类别将与 Album_Categories 模型一起保存。我希望 Gallery 模型知道存在哪些类别,并能够选择它想要使用的类别。
一旦它选择了一个类别,它应该能够访问与该类别关联的相册和相册的图像,它们通过和 Album_Images 连接表链接。即使删除了最初创建类别的专辑或画廊,该类别也应该能够继续存在,以便其他专辑或画廊以后可以利用它。
我的感觉是,每当创建一个独特的类别时,都应该通过 Category_Galleries 模型连接到 Gallery,但是在我使用通过自己特定的连接表连接到 Gallery 和 Album 的图像时,Gallery 不知道Album_images 连接,所以我假设共享由另一个创建的类别的知识是相同的。
任何帮助我理解这一点的方法将不胜感激。
编辑:型号代码
class User < ActiveRecord::Base
has_many :images, dependent: :destroy
has_many :galleries, dependent: :destroy
has_many :albums, dependent: :destroy
has_many :categories, dependent: :destroy
accepts_nested_attributes_for :images, :galleries, :albums, :categories, allow_destroy: true
accepts_attachments_for :images, attachment: :file, append: true
end
class Image < ActiveRecord::Base
belongs_to :user
has_many :gallery_images, dependent: :destroy
has_many :galleries, through: :gallery_images
has_many :album_images, dependent: :destroy
has_many :albums, through: :album_images
attachment :file, type: :image
validates :file, presence: true
end
class Album < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
has_many :album_galleries
has_many :galleries, through: :album_galleries # , dependent: :destroy
has_many :album_images, dependent: :destroy
has_many :images, through: :album_images
has_many :album_categories
has_many :categories, through: :album_categories
accepts_attachments_for :images, attachment: :file, append: true
accepts_nested_attributes_for :images
end
class Gallery < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
has_many :gallery_images, dependent: :destroy
has_many :images, through: :gallery_images
has_many :album_galleries, dependent: :destroy
has_many :albums, through: :album_galleries
accepts_attachments_for :images, attachment: :file, append: true
accepts_nested_attributes_for :images
end
class Category < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
has_many :albums, through: :album_categories
has_many :album_categories
end
class GalleryImage < ActiveRecord::Base
belongs_to :gallery
belongs_to :image
end
class AlbumCategory < ActiveRecord::Base
belongs_to :category
belongs_to :album
end
class AlbumGallery < ActiveRecord::Base
belongs_to :gallery
belongs_to :album
end
class AlbumImage < ActiveRecord::Base
belongs_to :album
belongs_to :image
end
【问题讨论】:
-
请添加您的模型代码,特别是关联定义。
-
画廊是否有自己的图像集,还是由所有相关的专辑图像推导出来的?
-
如果类别关联到一个画廊,而相册关联到一个类别,那么您可以通过检查画廊所有类别的所有相册的所有图像来找到与画廊替代关联的所有图像.
-
@hypern 现在画廊有它自己的图像,但我一直在拼凑这个,我开始考虑删除这方面并转向画廊只有通过共享的相册提供图像具有该特定画廊的类别。编辑:我刚刚看到您的第二个回复,您在第二个回复中描述的是我的目标,但现在我不知道如何与相册和图库共享类别。
标签: ruby-on-rails postgresql polymorphic-associations jointable