2012-07-17 70 views
0

我試圖讓所有的@participants性別是男性或女性。 我剛剛浮出水面,現在深入挖掘所有可能性,但發現很難完成此查詢。activerecord newbie;獲取所有性別男性/女性的個人資料?

  • 用戶(USER_ID)has_profile
  • 輪廓belongs_to的用戶
  • 參與者(participant_id)belongs_to的用戶,配置文件

我試着去獲得所有與participant_id參加其中有輪廓(USER_ID)他們有性別=「男性」或「女性」

如何獲得充滿結果的@participants_male最簡短的方法是什麼?

我不知道如何擺脫與where語句的關係,任何人都可以幫助我在正確的方向?謝謝!

@participants_male = Participant.where(

回答

2

性別是用戶表中的一列嗎?如果是這樣的:

@participants_male = Participant.includes(:users).where("users.gender = 'male'") 

編輯 - 如果性別是在曲線表:

@participants_male = Participant.includes(:profiles).where("profiles.gender = 'male'") 

我也建議檢查this railscast瞭解joinsincludes之間的差異,這樣你就可以決定什麼你的情況更好。

+0

沒有性別是在Profile.gender模型 – Rubytastic 2012-07-17 22:17:31

+0

我已經更新了我的答案.... – gabrielhilal 2012-07-17 22:34:50

+0

好所以嘗試了這一點,閱讀關於連接vs包括。你的例子似乎是邏輯,但卻拋出了一個「名爲'profiles'的關聯沒有被發現;也許你拼錯了它?所以它與參與者沒有關聯 – Rubytastic 2012-07-17 23:19:03

2

active record queries的導軌指南是一個很好的資源。您的查詢會是這個樣子:

@males = Participant.joins(:profiles).where('profiles.gender = "male"') 

或者你可以使用的includes代替joins

@males = Participant.includes(:profiles).where('profiles.gender = "male"') 

看看includes vs joins,看看哪個適合你的具體情況。

相關問題