我有 2 個表,一個用戶和其他朋友,我建立了一種關系,以便用戶可以互相關注。
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 ,即友誼何時形成。
uj5u.com熱心網友回復:
當您也想顯示好友的創建日期時,最簡單的方法是加載用戶的好友而不是他們的好友。
代替
@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 查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/336760.html
