2011-04-12 64 views
1

如何將對象與下面的模型連接起來?model/sql join in rails 3

 
User 
has_many messages 

Message 
belongs_to user 

Thread 
has_many messages 

我試圖讓屬於用戶X的所有主題我想加盟上message.user_id = user.user_idthread.message_id = message.message_id。我可以使用find_by_sql來做到這一點,但我試圖避免這種情況。

感謝

+0

不應該'消息'還'belongs_to:線程?'? – 2011-04-12 15:43:35

回答

0

下面應該工作:(請注意,我添加了缺少message belongs_to :thread

class User < ActiveRecord::Base 
    has_many :messages 
    has_many :threads, :through => :messages 
end 

class Message < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :thread 
end 

class Thread < ActiveRecord::Base 
    has_many :messages 
    has_many :users, :through => :messages 
end 

這應該允許你做my_user.threadsmy_thread.users

您可以通過Rails GuidesAPI瞭解關於has_many :through的更多信息。

2

假設你Message模式也belongs_to :thread,那麼你應該能夠把一個has_many :threads, :through => :messagesUser模型。然後你可以做user.threads來獲得所有相關的線程。