Search code examples
ruby-on-railsruby-on-rails-3activerecordrelationshipsmodel-associations

Creating Rails associations


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

  • User has many photo albums
  • Photo Album has many photos
  • Users can follow someone else's specific photo album (and indirectly they end up following the photo album's owner) and have the photos show up in a "news feed" type scenario, so there has to be some sort of relationship set up between them

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:

  • Jane has 2 photo albums, "Jane's Public Stuff" and "Jane's Private Stuff" with photos in each of them.
  • Bob follows ONLY "Jane's Public Stuff" so how can I return the photos from only that photo album via ActiveRecord associations?

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!


Solution

  • 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