除了许多文章和文档遍及互联网,我已阅读了很多关于连接表,STI表和多态关联的问题和解答。虽然我学到了很多东西,但我仍然对我在这种情况下应该做的事感到困惑。我可能已经阅读了答案,但并不知道我正在阅读答案,但我想看看是否有人能够帮助我理解我应该在这里做什么。加入表格混淆Ruby on Rails
我有一个Gallery模型,一个Album模型,一个Image模型和一个Category模型。这些都嵌套在用户模型中。
当您创建一个专辑时,为它指定一个类别,并用一个Album_Categories模型保存它们。我希望Gallery模型知道类别的存在,并能够选择想要使用的类别。
一旦它选择一个类别,它应该能够访问与该类别相关联的专辑和通过和Album_Images连接表链接的专辑的图像。即使最初创建的“专辑”或“图库”被删除,该类别也应该能够继续存在,以便其他专辑或图库可以在以后使用。
我的感觉是,无论什么时候创建一个独特的类别,应该如何通过Category_Galleries模型连接到Gallery,但是在使用连接到具有其自己的特定连接表的Gallery和Album的图像时,Gallery不知道一个Album_images连接,所以我假设分享由另一个创建的类别的知识将是相同的。
任何方式来帮助我unerstand这将不胜感激。
编辑:型号代码
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
如果类别与画廊和相册关联到一个类别,那么您可以通过检查画廊所有类别的所有相册中的所有图像,找到所有与代理相关的图像。 – hypern