[英]ActiveRecord Rails querying efficiently
看一下這個問題 。
id = current_user.id
@given_gifts = User.find(id).following_users.includes(:given_gifts).collect{|u| u.given_gifts}.flatten
@received_gifts = User.find(id).following_users.includes(:received_gifts).collect{|u| u.received_gifts}.flatten
@gifts = @given_gifts.zip(@received_gifts).flatten.compact
我正在嘗試檢索當前用戶遵循的所有用戶接收和提供的禮物清單。 有一個更好的方法嗎? 結果全部亂七八糟,並且顯示了一些重復項。 我正在嘗試做一個可以分頁的有效查詢。
在我的User.rb中
has_many :given_gifts, class_name: 'Gift', foreign_key: 'giver_id'
has_many :received_gifts, class_name: 'Gift', foreign_key: 'receiver_id'
acts_as_followable
acts_as_follower
在我的Gift.rb中
belongs_to :giver, class_name: 'User'
belongs_to :receiver, class_name: 'User'
對於以下功能,我正在使用actions_as_follower gem 。
嘗試這樣的事情:
following_user_ids = current_user.following_users.pluck(:id)
Gift.where("(giver_id IN ?) OR (receiver_id IN ?)",
following_user_ids, following_user_ids).order(:created_at)
基本上,這將獲取following_users id的列表,然后使用OR查詢獲取列表中任何用戶給予或接收的禮物。
該查詢的性能將取決於基礎數據庫和您正在處理的記錄數。 但是對於一小部分以下的用戶(<= 100),通常效果會很好。 隨着following_user_ids數量的增加,性能將下降。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.