簡體   English   中英

ActiveRecord:如何從聯接查詢中選擇單個列?

[英]ActiveRecord: how to select a single column from join query?

user has_many devices

編輯: device有一個registration_id字段

我想要一個用戶設備的所有registration_id數組,然后是某個用戶。

我正在努力:

@user.followers.join(:devices).select("devices.registration_id")

但這似乎可行,我該如何查詢?

我不確定,但是認為這應該有效:

@user.followers.map { |f| f.devices.pluck(:registration_id) }.flatten

upd :為了減少查詢數量,我可以提供以下解決方案:

Device.where(user_id: @user.followers.pluck(:id)).pluck(:registration_id)
     try by swapping
        @user.select("devices.registration_id").followers.join(:devices)

您可能需要重新檢查設備與注冊之間的關聯

Device
  belongs_to :user
  has_one :registration  #but in this case the device_id should be in Registration

考慮registration_id是設備的字段

 arr = @user.followers.collect(&:id)
 @user.devices.collect{|d| d.registration_id if arr.include?d.follower_id}
@user.followers.join(:devices).select("devices.registration_id")

如果在.join之后加上en,應該可以使用。 它稱為.joins(“ devices”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM