Trouble with Rails has_many relationships

∥☆過路亽.° 提交于 2019-12-10 16:51:28

问题


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


回答1:


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



回答2:


tried following.page instead of followings.pages ?




回答3:


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.



来源:https://stackoverflow.com/questions/2535704/trouble-with-rails-has-many-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!