paint-brush
How To Show User Friends Posts Using Ruby on Railsby@othmane-namani
571 reads
571 reads

How To Show User Friends Posts Using Ruby on Rails

by Othmane NamaniDecember 18th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How To Show User Friends Posts Using Ruby on Ruby on. Rails feature has created a mutual friendship feature. All that you need is to find the right association between User model and Post Model. Ruby On. Rails association is very simple and natural: A user has many friends. A friend has many posts, so the user’s friends’ posts are the. collection of all the friends. posts. The idea of friends�’. posts is simple: Users have a lot of posts. Users have friends with many posts.
featured image - How To Show User Friends Posts Using Ruby on Rails
Othmane Namani HackerNoon profile picture

In this post, I’ll explain a trick that will give your web application the ability to show friends’ posts.

Notes: In this example, we assume these are implemented in your application:

  1. User and Post models implemented.
  2. A mutual friendship feature has created.

If you need to learn how to install this feature you can check for this post.

The Idea of friends’ posts is very simple. All that you need is to find the right association between User model and Post Model.

So if you think about this association, it looks very simple and natural:

A user has many friends. A friend has many posts, so the user’s friends’ posts are the collection of all the friends’ posts.

But the question is, how to put in place this association with Ruby on Rails real example?

This is our User model:

class User < ApplicationRecord
    has_many :posts, dependent: :destroy
    has_many :friendships, dependent: :destroy
    has_many :friends, through: :friendships, dependent: :destroy
    ...
end

So, if you learn this Ruby on Rail snippet of code, you will understand that :

  • A user could have a lot of posts.
  • A user has a lot of friends.
  • A friend which is also a user, has a lot of posts.

So from these associations, we can create our association with Ruby On Rails like this:

class User < ApplicationRecord
    ...
    has_many :friends_posts, through: :friends, source: :posts
    ...
end

You can understand

through:
and
source: 
methods on this OSF post.

In console :

If we have a

user1 
instance, we could show user friends posts like this:
user1.friends_posts
.

Finally, this is a link to learn more about Ruby on Rails Associations:

https://guides.rubyonrails.org/association_basics.html

Project: Rails association for better understanding:

https://www.theodinproject.com/courses/ruby-on-rails/lessons/associations#project-2-private-events

Enjoy coding on Rails!! :)