我很难理解如何创建以下关联:
- 用户有很多相册
- 相册有很多照片
- 用户可以关注其他人的特定相册(间接地,他们最终会关注相册的所有者)并将照片显示在“新闻提要”类型的场景中,因此他们之间必须建立某种关系
这是我的关联:
class User < ActiveRecord::Base
has_many :photo_albums
has_many :photos
has_many :relationships, :foreign_key => "follower_id",
:dependent => :destroy
has_many :reverse_relationships, :foreign_key => "followed_id",
:class_name => "Relationship",
:dependent => :destroy
has_many :followings, :through => :relationships, :source => :followed
has_many :followers, :through => :reverse_relationships, :source => :follower
end
class PhotoAlbum < ActiveRecord::Base
belongs_to :user
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :photo_album
end
class Relationship < ActiveRecord::Base
belongs_to :follower, :foreign_key => "follower_id", :class_name => "User"
belongs_to :followed, :foreign_key => "followed_id", :class_name => "User"
end
我怎样才能使它可以从用户关注的相册中获取所有照片?
例子:
- Jane 有 2 个相册,“Jane's Public Stuff”和“Jane's Private Stuff”,每个相册中都有照片。
- Bob 只关注“Jane's Public Stuff”,那么我如何才能通过 ActiveRecord 关联仅从该相册返回照片?
类似的东西bob.followings.photos
只返回 Bob 正在关注的相册中的照片……甚至bob.followings.photo_albums
是获取 Bob 正在关注的所有相册的集合
我知道要做到这一点可能还有很长的路要走,但是有没有更简单的方法使用 ActiveRecord 关联?
感谢您提供的任何建议或指导!对此,我真的非常感激!