我有这个复杂的数据模型,我想使用活动记录模型对象来表示它。
USER(user_id)
可以发帖。以USER_POST(post_id, user_id(fk))
为代表其他用户可回复帖子。我将其封装在CONVERSATION(conversation_id, post_id(fk), responded_by_user_id(fk))
中.原始发布和响应者之间交换的所有消息(作为对话的一部分)都MESSAGES(message_id, conversation_id, message_text)
。
我的担忧来自这样一个事实,即口头海报导航到消息通过
user->user_posts->conversation->messages
响应方导航到消息时
的位置 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
}
如果您发现这种方法有任何问题,您能告诉我吗?如果您能为此提出任何替代方法,我将不胜感激。
提前谢谢。
你真正拥有的是User
、Post
(不知道为什么最初是UserPost
)、Conversation
和Message
:
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
请记住,这未经测试,仅供参考。