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!
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