Ruby on rails Rails:活动记录通过不同路径对一对多(深度嵌套)进行建模
我有一个复杂的数据模型,我想用活动记录模型对象来表示它Ruby on rails Rails:活动记录通过不同路径对一对多(深度嵌套)进行建模,ruby-on-rails,Ruby On Rails,我有一个复杂的数据模型,我想用活动记录模型对象来表示它 用户(用户id)可以发布。由USER\u POST(POST\u id,USER\u id(fk))表示 其他用户可以回复帖子。我将其封装在一个对话中(对话id,帖子id(fk),由用户id(fk)响应)。 原始帖子和回复者之间交换的所有消息(作为对话的一部分)都进入消息(message\u id、conversation\u id、message\u text) 我的担忧来自于这样一个事实:orinal海报通过 user->user\u
用户(用户id)
可以发布。由USER\u POST(POST\u id,USER\u id(fk))表示
其他用户可以回复帖子。我将其封装在一个对话中(对话id,帖子id(fk),由用户id(fk)响应)
。
原始帖子和回复者之间交换的所有消息(作为对话的一部分)都进入消息(message\u id、conversation\u id、message\u text)
我的担忧来自于这样一个事实:orinal海报通过
user->user\u posts->对话->消息
当响应者通过
user->conversation->messages
从用户到消息有多条路径
我试图在活动记录模型中表示对象。以下是我能想到的
User{
has_many :user_posts
has_many :conversations #for the case where is not through user_posts
}
UserPost{
belongs_to :user
has_many :conversations
}
Conversation{
belongs_to :user #responded_by_user
belongs_to :user_post #this links to original posted user
has_many :messages
}
Message{
belongs_to :conversation
}
如果您发现这种方法有任何问题,请告诉我?如果您能为这一点提出任何替代方法,我也将不胜感激
提前感谢。看起来你真正拥有的似乎是用户
,帖子
(不确定它最初是用户帖子
),对话
,以及消息
,其中:
class User
has_many :posts
has_many :conversations
has_many :messages, through: :conversations
// If you want a user's conversations where they made the original post
def conversations_as_poster
self.conversations.joins(:posts).where("post.user_id = ?", self.id)
end
end
请记住,本文件未经测试,仅供参考
class Post
belongs_to :user
has_many :conversations
end
class Conversation
belongs_to :user
belongs_to :post
has_many :messages
end
class Message
belongs_to :conversation
belongs_to :user
end