這是我的兩個模型:
收藏:
class Collection < ActiveRecord::Base
has_many :children, class_name: "Collection", foreign_key: "parent_id"
belongs_to :parent, class_name: "Collection", foreign_key: "parent_id", optional: true
has_many :albums, dependent: :nullify
end
專輯:
class Album < ActiveRecord::Base
belongs_to :collection, optional: true
has_many :photos, dependent: :destroy
end
我需要一種方法來查找父收藏中的所有專輯和/或收藏。
關于我如何做到這一點的任何想法?
這將允許我訪問父集合中所有照片的串列等。
uj5u.com熱心網友回復:
access a list of all the photos within a parent Collection
第一種方法,從父集合遞回呼叫 get_photos 到它的子集合,然后是它的孫子集合,依此類推......直到沒有更多的子集合。
class Collection < ActiveRecord::Base
# ...
def get_photos
albums.map(&:photos).flatten.tap |photos|
photos << children.map(&:get_photos).flatten
end
end
end
這可能會呼叫許多查詢。
第二條本辦法,遷移集合表添加collection path列,因此,如果父集合c1ID為1,其路徑是/1,它的孩子,為的情況下,c2(ID:2)和c3(ID:3),那么C2路徑/1/2和c3路徑/1/3,等等... 每次在父集合下創建子集合時,都設定其路徑#{parent_path}/#{id}。
現在您可以使用查詢where('path LIKE ?', "#{parent_path}/%")來獲取父集合的所有子集合。
class Collection < ActiveRecord::Base
# ...
def get_photos
collection_ids = where('path LIKE ?', "#{self.path}/%").pluck(&:id)
album_ids = Album.where(collection_id: collection_ids).pluck(&:id)
Photo.where(album_id: album_ids).all
end
end
如果您只想呼叫一個查詢,則可以將集合路徑直接添加到 Photo 表中。
根據書SQL Anti-pattern,你的問題是Naive Trees(總是依賴于一個人的父母)。第二種方法是它的一種解決方案 -Path Enumeration其他方法是Nested Sets和Closure Table。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398135.html
下一篇:Ruby中的物件方法是什么
