【发布时间】:2010-10-12 05:22:55
【问题描述】:
我确实在 SO 上发现了一些关于 Rails 关联的问题,这些问题有点像我的问题,但在我的一生中,我似乎无法理解如何使用 belongs_to 多个模型。
这是我想要的表结构:
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
这是正确的方法吗?
【问题讨论】:
-
如何继续保存 cmets?
-
天啊,我学习 Rails 已经 7 年了(谢谢!)。要回答您的问题@MosesNdeda,您将实例化一个评论,分配用户和帖子对象,然后在评论对象上调用
save。
标签: ruby-on-rails activerecord belongs-to