在Rails中有多个has_many关联 [英] multiple has_many associations in Rails

查看:172
本文介绍了在Rails中有多个has_many关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say you have two models which can be associated in different ways:

用户有很多他们创建的会话。 (一对多)
用户有很多对话,他们涉及。 (多对多)

A User has many conversations they have created. (one to many) A User has many conversations in which they are involved. (many to many)

我的第一个想法是将创建对话的用户的ID存储在对话表中,并将参与对话的用户加入连接表。

My first thought was to store the id of the user who created the conversation in the conversations table, and associate users involved in a conversation in a join table.

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

这似乎是要求麻烦虽然。

This seems to be asking for trouble though.

这是正确的方法是什么?
基本上我想能够为那些由用户启动的用户使用user.conversations和user.started_conversations。

What's the right way to do this? Basically I want to be able to utilise user.conversations for those involved in and user.started_conversations for those started by user.

谢谢。

推荐答案

关键是不使用HABTM(其中所有关系都被认为是简单的),而是使用has_many,through,以指示表示会话的开始者/发起者的特定加入。

The key is to not use HABTM (where all relationships are considered simple), but to use has_many, through , with an attribute on the join to indicate the particular join that denotes the starter/initiator of the conversation.

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 )。

(assuming that you've got a join model called UserConversation with a boolean attribute called starter).

这样可以让你做如下操作:

This will let you do things like:

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

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

这篇关于在Rails中有多个has_many关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆