Rails中有多个has_many关联

doc*_*nge 1 database ruby-on-rails

假设你有两个模型可以以不同的方式关联:

用户有许多他们创建的对话.(一对多)用户有许多他们参与的对话.(很多很多)

我的第一个想法是在对话表中存储创建对话的用户的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
Run Code Online (Sandbox Code Playgroud)

这似乎是在寻找麻烦.

这样做的正确方法是什么?基本上我希望能够为那些参与者和user.started_conversations使用user.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
Run Code Online (Sandbox Code Playgroud)

(假设你有一个名为UserConversationboolean属性的连接模型starter).

这将让你做以下事情:

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

#get those started by the user, utilizing the attribute in the conditions
@user.initiated_conversations
Run Code Online (Sandbox Code Playgroud)