【发布时间】:2014-04-06 13:28:32
【问题描述】:
我的消息系统有很多问题。我很想得到一些帮助。除了 User Message 关系之外,它完全可以工作。我正在尝试将authored_messages 与User 和received_messages 与User 相关联。这样做的障碍是received_messages 应该经过两个不同的模型(ConversationUser 和Conversation),而authored_messages 应该是使用消息的user_id 字段的直接关系。她在这里:
模型
用户:
class User < ActiveRecord::Base
has_many(
:conversation_users,
inverse_of: :user,
dependent: :destroy
)
has_many(
:conversations,
through: :conversation_users
)
# has_many :messages ?
# has_many( ?
# :received_messages,
# class_name: "Messages",
# through: :conversations,
# source: :conversation_users
# )
消息:
class Message < ActiveRecord::Base
belongs_to :user # ?
belongs_to :recipient, class_name: "User" # ?
belongs_to(
:conversation,
inverse_of: :messages
)
has_many(
:conversation_users,
through: :conversation
)
accepts_nested_attributes_for :conversation
对话:
class Conversation < ActiveRecord::Base
has_many(
:messages,
inverse_of: :conversation
)
has_many(
:conversation_users,
inverse_of: :conversation
)
has_many(
:users,
through: :conversation_users
)
accepts_nested_attributes_for :messages
ConversationUser(连接模型):
class ConversationUser < ActiveRecord::Base
belongs_to(
:user,
inverse_of: :conversation_users
)
belongs_to(
:conversation,
inverse_of: :conversation_users
)
has_many(
:messages,
through: :conversation
)
delegate :users, to: :conversation
accepts_nested_attributes_for :conversation
迁移
用户
# None involved with messaging
留言
t.integer :user_id
t.integer :conversation_id
t.text :body
对话
# None, except the :id field. It helps relate messages and conversation_users
对话用户
t.integer :user_id
t.integer :conversation_id
在我看来,我会添加类似这样的内容 (how do I associate one model twice to another),但我很难将其应用到我的模型中。为了进一步阐明这些关联是如何工作的,这是一个非常简化的视觉效果:
users--->conversation_users
: |
: |
V V
messages<---conversation
我真的非常感谢我能得到的任何帮助,希望这个问题能帮助其他处理复杂关联的人!
编辑
我忘了提,但是这个消息系统可以有多少个收件人(conversation_users),就像发件人决定的一样。 (当发件人创建新对话时)
【问题讨论】:
-
快速提问 - 为什么多行关联有括号?
标签: ruby-on-rails activerecord associations