【发布时间】:2011-10-19 19:06:47
【问题描述】:
我很难理解如何创建以下关联:
- 用户有很多相册
- 相册有很多照片
- 用户可以关注其他人的特定相册(间接地,他们最终会关注相册的所有者)并让照片显示在“新闻提要”类型的场景中,因此必须在它们之间建立某种关系他们
这是我的联想:
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
如何才能从用户关注的相册中获取所有照片?
示例:
- 简有2个相册,《简的公事》和《简的私人》 东西”,每张照片中都有照片。
- Bob 只关注“Jane 的公开资料”,所以我怎样才能退回照片 通过 ActiveRecord 关联仅来自该相册?
bob.followings.photos 之类的东西只返回 Bob 正在关注的相册中的照片……甚至是 bob.followings.photo_albums 以获取 Bob 正在关注的所有相册的集合
我知道要做到这一点可能还有很长的路要走,但是有没有更简单的方法使用 ActiveRecord 关联?
感谢您提供的任何建议或指导!我真的很感激!
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord relationships model-associations