views:

232

answers:

3

I'm writing an app where a user can both create their own pages for people to post on, and follow posts on pages that users have created. Here is what my model relationships look like at the moment...

class User < ActiveRecord::Base

has_many :pages
has_many :posts
has_many :followings
has_many :pages, :through => :followings, :source => :user

class Page < ActiveRecord::Base

has_many :posts
belongs_to :user
has_many :followings
has_many :users, :through => :followings

class Following < ActiveRecord::Base

belongs_to :user
belongs_to :page

class Post < ActiveRecord::Base

belongs_to :page
belongs_to :user

The trouble happens when I try to work my way down through the relationships in order to create a homepage of pages (and corresponding posts) a given user is following (similar to the way Twitter's user homepage works when you login - a page that provides you a consolidated view of all the latest posts from the pages you are following)...

I get a "method not found" error when I try to call followings.pages. Ideally, I'd like to be able to call User.pages in a way that gets me the pages a user is following, rather than the pages they have created.

I'm a programming and Rails newb, so any help would be much appreciated! I tried to search through as much of this site as possible before posting this question (along with numerous Google searches), but nothing seemed as specific as my problem...

A: 

tried following.page instead of followings.pages ?

ohho
That seems to still give me an undefined method error (when I call it on a random user).
Tchock
A: 

As to your ideal, a simplified user model should suffice (:source should be inferred):

class User < ActiveRecord::Base
    has_many :pages
    has_many :posts
    has_many :followings
    has_many :followed_pages, :class_name => "Page", :through => :followings
end class

Now, using the many-to-many association :followings, a_user.followed_pages should yield a collection of pages.

Ajw
+2  A: 

You have defined the pages association twice. Change your User class as follows:

class User < ActiveRecord::Base
  has_many :pages
  has_many :posts
  has_many :followings
  has_many :followed_pages, :class_name => "Page", 
                 :through => :followings, :source => :user
end

Now let's test the association:

user.pages # returns the pages created by the user
user.followed_pages # returns the pages followed by the user
KandadaBoggu
Additionally, I'd probably rename `Page.user` to `Page.author` in order to disambiguate from `Page.users`.. or make `Page.users` into `Page.followers`.
jamuraa
Thanks! This solved it for me...
Tchock