【问题标题】:Creating Rails associations创建 Rails 关联
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 啊啊啊,我好近啊!谢谢!!!!现在我可以通过bob.followings.group_by(&amp;:user_id).count 之类的操作来了解他也关注了多少人。
    【解决方案2】:

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

    然后你可以通过user.friends.each do |f| 来检索user 的所有关注者,然后通过f.photos 获取每个关注者的所有照片。

    【讨论】:

    • 感谢您的回答,但我想看看是否可以在执行 do 循环或复杂 SQL 的漫长路线之前使用 AR 关联来完成此操作
    【解决方案3】:

    在用户模型中试试这个:

    def followings_photos
          Photo.where(:user_id => self.followings.collect(&:id))
    end
    

    【讨论】:

    • 感谢大卫,但它会收集他们关注的所有人的所有照片,即使他们没有关注照片所在的相册。我希望它只返回照片他们关注的相册
    • 我在原始问题中添加了一个示例以更好地解释它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2015-02-09
    • 2010-11-21
    相关资源
    最近更新 更多