Ruby on Rails Active Writing Syntax for Requesting Status Updates in a Twitter Style Application

I have a Twitter style app in which a user follows many people. This is achieved through self-referential association.

All this works very well, but my brain just died trying to figure out the active record syntax needed to list status updates (messages) from people whom the user follows in order in time in one request.

My user model looks like

class User < ActiveRecord::Base
    has_many :posts
    has_many :friendships
    has_many :friends, :through => :friendships
end

And the postal model

class Post < ActiveRecord::Base
    belongs_to :user
end

To complete the friendship model

class Friendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => "User"
 end

Ultimately I want to do

@ user.friends.reviews.all

+3
source share
2 answers

, User, Friend has_many: posts:

@user.friends.posts.find(:all, :order => "created_at DESC"

+1

, , @user.friends , .posts ( AR).

, , - User#friend_posts, , .

- :

def friend_posts
  posts = []
  friends.each { |friend| posts << friend.posts }
  posts
end
+1

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


All Articles