Problem with Rails has_many relationship

I am writing an application in which the user can create their own pages for people to post messages, and follow the messages on the pages created by users. Here's what my model relationship looks 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 problem arises when I try to make my way through relationships to create the homepage of the pages (and corresponding messages) that the given user sets (similar to how the Twitter homepage works when you log in - a page that provides you with a consolidated view of all the latest posts from the pages you follow) ...

I get a "method not found" error when I try to call followings.pages. Ideally, I would like to be able to call User.pages so that it gets the pages that the user is following, and not the pages that they created.

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

+4
source share
3 answers

You have defined the pages association twice. Modify the 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 test the association:

 user.pages # returns the pages created by the user user.followed_pages # returns the pages followed by the user 
+4
source

tried the following page instead of follow follow.pages?

0
source

As for your ideal, there should be a fairly simplified user model (: the source should be output):

 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 provide a collection of pages.

0
source

Source: https://habr.com/ru/post/1305413/


All Articles