简体   繁体   English

Rails —如何构建belongs_to / has_many关联?

[英]Rails — how to structure belongs_to/has_many associations?

Pretty simple question, I think: so I have a User model, a Product model, and a Comment model. 我认为这是一个非常简单的问题:所以我有一个User模型,一个Product模型和一个Comment模型。 I want the Users to be able to comment on specific products (like leave reviews for the products). 我希望用户能够对特定产品发表评论(例如对产品发表评论)。

Is this the correct structure? 这是正确的结构吗?

User
  has_many :comments

Product
  has_many :comments

Comment
  belongs_to :user
  belongs_to :product

Thanks. 谢谢。

yes it's correct if you want just comment on products, if you will comment on other model other than product, then use polymorphic association. 是的,如果您只想对产品发表评论,或者对产品以外的其他模型发表评论,那么使用多态关联是正确的。

also don't forget to add dependent: :destroy to destroy related comments if the product is destroyed or the user is destroyed 如果产品被销毁或用户被销毁,也不要忘记添加dependent: :destroy销毁相关注释

in Product and User model add dependent: :destroy 在产品和用户模型中添加dependent: :destroy

has_many :comments, dependent: :destroy

if you want other behavior than this, there is other options, from Doc : 如果您想要除此以外的其他行为,可以从Doc中找到其他选项:

:dependent :依赖

Controls what happens to the associated objects when their owner is destroyed: 控制销毁所有者时关联对象发生的情况:

 :destroy causes all the associated objects to also be destroyed :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute) :nullify causes the foreign keys to be set to NULL. Callbacks are not executed. :restrict_with_exception causes an exception to be raised if there are any associated records :restrict_with_error causes an error to be added to the owner if there are any associated object 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM