2011-09-30 65 views
1

我有以下內容,並試圖找出如何選擇用戶信息(問題結束時的SQL)。Rails 3.1和跨越三個表選擇

# only global_id and list_id 
class GlobalList < ActiveRecord::Base 
    set_table_name :globals_lists 
    belongs_to :list 
end 

# user_id 
class List < ActiveRecord::Base 
    has_many :global_lists 
    belongs_to :user 
end 

# email 
class User < ActiveRecord::Base 
    has_many :lists 
end 

我將如何選擇的用戶列表的電子郵件,假設我有一個global_id(即假設256的global_id,

select u.* from users u, lists l, globals_lists gl where gl.global_id=256 and gl.list_id=l.id and l.user_id=u.id) 

回答

1

試試這個:

User.includes({:lists => :global_lists}).where(['global_lists.global_id = ?', 256])

這將返回User對象,這似乎是您要查詢的內容,然後您可以從他們的.email屬性,在一個循環中,或者你需要它。

+0

是否有很好的來源/教程來顯示這些類型的查詢 - 我有很多這些,我需要從SQL端口。 thx – timpone

+0

良好的開端:http://api.rubyonrails.org/classes/ActiveRecord/Base.html – ctcherry

+0

thx - 儘管如此多的變化:-( – timpone