2016-09-14 65 views
0

我有一個模型配置文件,有一個與模型興趣的onetoone。如果我使用where查詢配置文件數組,那麼我將如何獲得由與最初查詢的配置文件相關的興趣組成的另一個獨立數組?Ruby on Rails:子查找找到的對象的關係對象數組?

喜歡的東西

@foundProfiles = Profile.where(field: data) 

@foundInterests = @foundProfiles.Interest.all 

這不起作用,但是這就是我試圖讓她的想法。

回答

2

。利用協會:

@foundProfiles = Profile.includes(:interest).where(field: data) 
# Eager load interest to avoid n + 1 queries 

@foundInterests = @foundProfiles.map(&:interest) 

編輯

如果您需要進一步查詢的Interest記錄,你可以這樣做:

@foundInterests = Interest.where(profile_id: @foundProfiles.map(&:id)) 

這將返回Interest記錄與@foundProfiles相關聯,您可以鏈where就可以了

+0

謝謝,我在黑暗的地圖功能。 –

+0

似乎我不能在@foundInterests上執行後續操作,雖然...它給了我一個沒有方法的地方,錯誤 –

+0

不,你不能。它會返回你陣列 –