r123454321
r123454321

Reputation: 3403

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

Upvotes: 0

Views: 118

Answers (1)

medBouzid
medBouzid

Reputation: 8382

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

in Product and User model add dependent: :destroy

has_many :comments, dependent: :destroy

if you want other behavior than this, there is other options, from 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

Upvotes: 1

Related Questions