Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails属于许多型号_Ruby On Rails_Activerecord_Belongs To - Fatal编程技术网

Ruby on rails Rails属于许多型号

Ruby on rails Rails属于许多型号,ruby-on-rails,activerecord,belongs-to,Ruby On Rails,Activerecord,Belongs To,我确实在网上找到了一些关于Rails关联的问题,这些问题有点像我的问题,但就我的一生而言,我似乎无法理解如何使用属于多个模型 这是我想要的表格结构: 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 th

我确实在网上找到了一些关于Rails关联的问题,这些问题有点像我的问题,但就我的一生而言,我似乎无法理解如何使用
属于
多个模型

这是我想要的表格结构:

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"
各协会:


这是正确的方法吗?

是的,这是正确的方法。

虽然并非总是“最佳”方法,但Rails提供了所谓的“最佳”方法。它阻止您在数据库中定义外键,因为xxx_id列引用了许多可能的表中的一个表中的id,而另一列指定了该表的模型名称,但它使关系在Rails中更加明确。此外,它将模型限制为只属于其他模型中的一个,而不是属于一个或多个,因为使用多个外键设置时可能会发生这种情况,而不需要一些额外的db魔法。

这是否需要一个联接表或任何东西。。。或者它会像他所展示的那样工作吗?这是一对多关系(一个用户有许多帖子等),因此不会。注释表应该是这样的:id user\u id post\u id和ofc content或其他什么。您可以键入has\u many:posts,:commentsQuestion:在第一篇帖子中,您将执行的操作:current\u user.post.build(params[:post])但是在评论中,如果没有带有帖子id的隐藏字段,您如何在评论中同时为用户id和帖子id添加属性?这个问题及其答案解释了如何很好地做到这一点:您如何继续执行评论保存?天哪,我学rails已经7年了(非常感谢!)。要回答您的问题@MosesNdeda,您需要实例化一条注释,分配用户和post对象,然后对注释对象调用
save
User
 has_many :posts
 has_many :comments

Post
 belongs_to :user
 has_many :comments

Comment
 belongs_to :user
 belongs_to :post