Rails 属于许多模型 [英] Rails belongs_to many models
本文介绍了Rails 属于许多模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我确实在 SO 上发现了一些关于 Rails 关联的问题,这些问题有点像我的问题,但就我的生活而言,我似乎无法理解如何使用 belongs_to
多个模型.
I did find some questions on SO about Rails associations that are somewhat like my question, but for the life of me I can't seem to understand how to use belongs_to
multiple models.
这是我想要的表结构:
User
id
Post
id
user_id #foreign key; a post belongs to a User aka "Who created this post"
Comment
id
user_id #foreign key; a comment belongs to a User aka "Who made this comment"
post_id #foreign key; a comment belongs to a Post aka "What post this comment is for"
还有协会:
User
has_many :posts
has_many :comments
Post
belongs_to :user
has_many :comments
Comment
belongs_to :user
belongs_to :post
这是正确的方法吗?
推荐答案
是的,这是正确的方法.
Yes that is the correct approach.
这篇关于Rails 属于许多模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文