Ruby-on-rails Rails 属于多种型号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3911890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:21:40  来源:igfitidea点击:

Rails belongs_to many models

ruby-on-railsactiverecordbelongs-to

提问by Zabba

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_tomultiple models.

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

Here's the table structureI intend to have:

这是我打算拥有的表结构

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"

And the associations:

协会

User
 has_many :posts
 has_many :comments

Post
 belongs_to :user
 has_many :comments

Comment
 belongs_to :user
 belongs_to :post

Is this the correct approach?

这是正确的方法吗?

回答by Maxem

Yes that is the correct approach.

是的,这是正确的方法。

回答by Zhenya Slabkovski

While not always the "best" approach, Rails offers what's called a Polymorphic belongs_to association. It prevents you from defining a foreign key in the database because the xxx_id column is referencing an id in one of many possible tables while another column designates the name of that table's model, but it makes the relationship more explicit in Rails. Also, it restricts the model to only belong to one of the other models, as opposed to belonging to one or more, as it would happen using the setup of multiple foreign keys without some additional db magic.

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