开发者

Trouble with Rails has_many relationships

开发者 https://www.devze.com 2022-12-25 03:00 出处:网络
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...

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 use开发者_开发技巧r 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...


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


tried following.page instead of followings.pages ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消