Rails6中User与好友的多对多关联如何获取created_at?

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

我有2个table,一个用户和其他朋友,我建立了一个关系,这样用户就可以互相关注了。

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

我已经在用户控制器中设置了@friends = current_user.friends 来获取我所有的朋友,但我还想获得建立友谊时的时间戳。

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

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

我想获取当前用户的所有好友以及 created_at 来自好友关系 table 即好友关系形成时间。

如果您还想显示友谊的创建日期,那么最简单的方法是加载用户的友谊而不是他们的朋友。

而不是

@friends = current_user.friends

你可以写

# 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 %>

顺便说一下,我在查询中添加了 include 以避免 N+1 查询。