2009-07-21 79 views
1

比方说,你有能以不同的方式相关联的两种模式:多个has_many关联

用户有他们创造了多次交谈。 (一对多) 用户有很多涉及他们的谈话。 (多对多)

我的第一个想法是将在会话表中创建会话的用户的ID存储在会话表中,并将会话中涉及的用户关联到联接表中。

class User < ActiveRecord::Base 
    has_many :conversations 
    has_and_belongs_to_many :conversations 
end 

class Conversation < ActiveRecord::Base 
    belongs_to :user 
    has_and_belongs_to_many :users 
end 

虽然这似乎是要求麻烦。

什么是正确的方法来做到这一点? 基本上我希望能够为那些涉及user.conversations和user.started_conversations的用户启动。

谢谢。

回答

7

关键是不使用HABTM(其中所有关系都被认为是简单的),而是使用has_many through和连接上的属性来指示表示对话的起始者/发起者的特定连接。

class User < ActiveRecord::Base 

    has_many :user_conversations 
    has_many :conversations, :through => :user_conversations 
    has_many :initiated_conversations, :through => :user_conversations, 
      :source => :conversation, 
      :conditions => ["user_conversations.starter = ?", true] 

end 

(假设你有所谓的UserConversation一个名为starter一个布尔值属性的连接模型)。

这将让你做这样的事情:

#get conversations users, including the starter 
@user.conversations 

#get those started by the user, utilizing the attribute in the conditions 
@user.initiated_conversations