2012-03-13 44 views
1

用戶has_one UserProfile has_one社區。rails 3.1:activerecord如何通過has_one連接的3個表系列進行查詢?

給定一個community_id,我需要Users表中的電子郵件列表。

如何獲取所有User.email的列表,其中community_id = 5?

我能找到的最好的(它的工作)是:

User.select(:email).joins(:user_profile).merge(UserProfile.for_community(5)) 

但似乎蠻力...有沒有辦法做的東西沿着這下方的線條更簡單?

User.user_profile.community(5) 

回答

1

我不認爲你知道你的代碼做什麼...

如果UserProfile has_one社區,那麼社區表必須有一個標題爲user_id的列。這意味着只有一個用戶與任何給定的社區ID相關聯。

要解決您的問題,如上所述,您可以將用戶方法委託給user_profile。

class Community < ActiveRecord::Base 
    belongs_to :user_profile 
    delegate :user, to: :user_profile 
end 

那麼你可以做Community.find(community_id).user.email

希望有所幫助。

+0

AFAIK如果UserProfile has_one社區,那麼UserProfile有一個名爲community_id的字段 - 而不是其他方式 - 對嗎? – jpwynn 2012-03-13 05:16:36

+1

不是。如果ModelX has_one:model_y,則外鍵model_x_id應位於model_ys表中。 – Max 2012-03-13 11:03:51

+0

感謝您指導我正確的方向,這是我遇到的另一個問題的來源。 – jpwynn 2012-03-13 17:03:50

0

我覺得從另外的方向的可能完成你在找什麼:

Community.find("5").user_profile.user.emails 
+0

thx,但沒有給出錯誤說user_profile是未知的社區方法。 user_profiles可以工作,但用戶對於user_profiles是一個未知的方法。和.user_profile.users給出相同的錯誤(用戶是use_profiles的未知方法) – jpwynn 2012-03-13 07:28:17

+0

哦所以社區有很多UserProfiles和一個UserProfile有很多用戶? – 2012-03-13 08:29:17