user
has_many devices
。ActiveRecord:如何從連接查詢中選擇單個列?
編輯:device
有registration_id
場
我想獲得用戶,然後某個用戶設備的所有registration_id
的數組。
我想:
@user.followers.join(:devices).select("devices.registration_id")
但似乎工作, 我怎麼能做到這一點查詢?
user
has_many devices
。ActiveRecord:如何從連接查詢中選擇單個列?
編輯: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)
它返回所需的結果,但它查詢每個用戶ID的設備表,因此對於n個用戶有n個查詢。有沒有更有效的方法來做到這一點? –
我已經添加了另一個解決方案 – ck3g
try by swapping
@user.select("devices.registration_id").followers.join(:devices)
NoMethodError:私人方法'選擇'要求#<用戶:0x00000004fa3440> –
您可能要重新檢查設備和註冊之間的關聯
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")
的領域,如果你。加入後把多餘的連接S的關係的工作。它被稱爲.joins(「devices」)
'Device.find_all_by_user_id(@ user.follower_ids)''?你會得到整個設備模型,但這很重要嗎? –