Search code examples
mysqlruby-on-railsrubyruby-on-rails-4ruby-on-rails-5

How to get the created_at of the many to many association of User with friends in Rails 6?


I have 2 tables, one user and other friends, I have set up a relationship such that the user can follow one another.

class Friendship < ApplicationRecord
 belongs_to :user
 belongs_to :friend, class_name: "User"
end

class User < ApplicationRecord
 has_many :posts
 has_many :friendships
 has_many :likes
 has_many :comments
 has_many :friends, through: :friendships

I have set up @friends = current_user.friends in the user's controller which fetches me all the friends, but I also want to get the timestamp when the friendship was formed.

Friendship Table Attributes: id, user_id, friend_id, created_at, updated_at

User Table Attributes: id, email, password, ..., created_at, updated_at

I want to get the all the current user's friends and also the created_at from the friendship table i.e. when the friendship was formed.


Solution

  • When you want to present the friendship's creation date too then the easiest way would be to load the user's friendships instead of their friends.

    Instead of

    @friends = current_user.friends
    

    you could write

    # in your controller
    @friendships = current_user.friendships.include(:friend)
    
    # in the view
    <% @friendships.each do |friendship| %>
      The friend <%= friendship.friend %>
      since <% friendship.created_at %>
    <% end %>
    

    Btw I added the include to the query to avoid N+1 queries.