ZeNewb
ZeNewb

Reputation: 435

Creating Rails associations

I'm having a hard time understanding how to create the following associations:

Here's the associations I have:

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

How can I make it to where I can just get all the photos from the photo albums the user is following?

Example:

Something like bob.followings.photos that returns photos from ONLY the photo albums that Bob is following... or even bob.followings.photo_albums to get a collection of all the photo albums that Bob is following

I know there's probably a long way to do this, but is there an easier way using ActiveRecord associations?

Thanks for any advice or guidance you can provide! I really appreciate it!

Upvotes: 1

Views: 246

Answers (3)

MrTheWalrus
MrTheWalrus

Reputation: 9700

The way you have it set up, following associates a User to another User, not a User to a PhotoAlbum, which is what you describe. It sounds as though you want

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

With that done, a slight modification of davidb's answer should give you what you want:

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

Upvotes: 2

davidb
davidb

Reputation: 8954

try this in User model:

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

Upvotes: 1

rocketscientist
rocketscientist

Reputation: 2488

You may want to look at the amistad gem at https://github.com/raw1z/amistad, which gives you friends and friendships functionality. In your case, a friend would be a follower.

Then you can do something like user.friends.each do |f| to retrieve all the followers of user and then f.photos to get all the photos from each follower.

Upvotes: 1

Related Questions