2012-10-09 29 views
0

user has_many devicesActiveRecord:如何從連接查詢中選擇單個列?

編輯:deviceregistration_id

我想獲得用戶,然後某個用戶設備的所有registration_id的數組。

我想:

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

但似乎工作, 我怎麼能做到這一點查詢?

+0

'Device.find_all_by_user_id(@ user.follower_ids)''?你會得到整個設備模型,但這很重要嗎? –

回答

1

我不知道,但認爲這應該工作:

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

UPD:爲了儘量減少查詢數,我可以提供這個解決方案:

Device.where(user_id: @user.followers.pluck(:id)).pluck(:registration_id) 
+0

它返回所需的結果,但它查詢每個用戶ID的設備表,因此對於n個用戶有n個查詢。有沒有更有效的方法來做到這一點? –

+0

我已經添加了另一個解決方案 – ck3g

0
 try by swapping 
     @user.select("devices.registration_id").followers.join(:devices) 
+0

NoMethodError:私人方法'選擇'要求#<用戶:0x00000004fa3440> –

0

您可能要重新檢查設備和註冊之間的關聯

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} 
+0

小心添加一些註釋到您的代碼?也許它有效,但評論它將有助於其他人尋找相同的問題 – Yaroslav

+0

我想說這個協會是錯誤的。如果設備has_one:註冊,那麼device_id應該在註冊 –

+0

編輯你的答案並添加任何說明 – Yaroslav

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

的領域,如果你。加入後把多餘的連接S的關係的工作。它被稱爲.joins(「devices」)

相關問題