【问题标题】:multiple has_many associations in RailsRails 中的多个 has_many 关联
【发布时间】:2009-07-21 02:44:25
【问题描述】:

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

用户创建了许多对话。 (一对多) 一个用户有许多他们参与的对话。 (多对多)

我的第一个想法是将创建对话的用户的 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 用于由用户启动的人。

谢谢。

【问题讨论】:

    标签: ruby-on-rails database


    【解决方案1】:

    关键是不要使用HABTM(所有关系都被认为是简单的),而是使用has_many,通过,在连接上带有一个属性来指示表示对话开始者/发起者的特定连接。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多