1

我很难理解如何创建以下关联:

  • 用户有很多相册
  • 相册有很多照片
  • 用户可以关注其他人的特定相册(间接地,他们最终会关注相册的所有者)并将照片显示在“新闻提要”类型的场景中,因此他们之间必须建立某种关系

这是我的关联:

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 关联?

感谢您提供的任何建议或指导!对此,我真的非常感激!

4

3 回答 3

2

您设置它的方式是将用户与另一个用户相关联,而不是将用户与相册相关联,这就是您所描述的。听起来好像你想要

class Relationship < ActiveRecord::Base
  belongs_to :follower, :foreign_key => "follower_id", :class_name => "User"
  belongs_to :followed, :foreign_key => "photo_album_id", :class_name => "PhotoAlbum"
end

完成后,对 davidb 的答案稍作修改应该会给你你想要的:

def followings_photos
      Photo.where(:photo_album_id => self.followings.collect(&:id))
end
于 2011-10-19T20:43:01.910 回答
1

您可能想查看https://github.com/raw1z/amistadamistad上的gem ,它为您提供了朋友和友谊功能。在您的情况下,朋友将成为追随者。

然后你可以做一些事情,比如user.friends.each do |f|检索所有关注者user,然后f.photos从每个关注者那里获取所有照片。

于 2011-10-19T19:25:13.987 回答
1

在用户模型中试试这个:

def followings_photos
      Photo.where(:user_id => self.followings.collect(&:id))
end
于 2011-10-19T19:29:11.833 回答