2012-04-06 29 views
1

我試着去弄清楚如何做:新手:activerecord加入?一些幫助將SQL語句的ActiveRecord

  • 組 的has_many參與者
  • 參與者 belongs_to的組
  • 用戶 has_profile
  • 輪廓 belongs_to的用戶

現在我試圖讓所有參加者從group.id ='1'和其中participant.profile.gender ='x'

這將如何轉換爲活動記錄?我已經挖掘了文檔,但不是一個sql大師,也不是一個AR大師。任何人都可以將我指向正確的方向?這對了解如何做到這一點非常有幫助。 困惑

+0

是partecipants用戶還是個人檔案? – 2012-04-06 22:56:27

+0

參與者是唯一的user_id group_id created_at updated_at基於user_id我抓住那裏配置文件,然後profile.gender – Rubytastic 2012-04-06 22:57:31

回答

1

我認爲你可以做這樣的事情

Participant.where(:group_id => 1).where(:profile=>{:gender=>'x'}) 

更新:由於參與者是連接表你就需要更改:

Participant.where(:group_id => 1).where(:user=>{:profile=>{:gender=>'x'}}) 

您還需要添加一個belongs_to:用戶至參與者

+0

thx試圖,現在我看到它應該如何做在軌道非常乾淨。但隨後參與者加載(0.8毫秒)SELECT'參與者'。*從'參與者'WHERE'參與者'.'group_id' = 1 AND'profile'.'gender' ='男性' ActiveRecord :: StatementInvalid:Mysql2 :: Error :'where子句'中的未知列'profile.gender':SELECT'participants'。* FROM'participants' WHERE'participants'.'group_id' = 1 AND'profile'.'gender' ='male' 我明白了profile.gender存在時出錯,添加關係爲什麼會中斷? – Rubytastic 2012-04-06 23:18:07

+0

是該表名爲profiles?在這種情況下,嘗試在where子句中複用它。您可能還需要添加.includes(:users).includes(:profiles) – 2012-04-06 23:59:40

+0

還有一點需要注意:如果您知道確切的sql會爲您提供所需的結果,則可以使用find_by_sql。你放棄了一些可移植性,但它通常比使用「Rails方式」更快 – 2012-04-07 14:01:52