Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

has and belongs to many - has_and_belongs_to_many in Rails

Is there anything explicitly wrong with using has_and_belongs_to_many associations in rails instead of has_many :through? I'm aware of these articles describing differences and work arounds, but they are from 2006. From things I've read on SO, it seems like people think that habtm is old and clunky, but what if a simple many to many join with no model necessary is what you're looking for?

Thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

has_and_belongs_to_many is meant for simple many-to-many relationships.

has_many :through, on the other hand, is meant for indirect one-to-many relationships, or many-to-many relationships with properties.

If you're only looking for a simple many-to-many relationship, I can't see any reason not to use has_and_belongs_to_many.

Example many-to-many relationship:

User belongs to zero or more groups, and group has zero or more members (users).

Example many-to-many relationship with properties:

User belongs to zero or more groups, and group has zero or more members with ranks.

For example, Alice might be an Administrator in Group A, and a Moderator in Group B. You can hold this property in the join table.

Example indirect one-to-many relationship:

A category has zero or more sub-categories, and each sub-category has zero or more items.

A category therefore has zero or more items through its sub-categories.

Consider these categories:

Food → Fruits, Vegetables
Fruits → Apple, Orange, etc.
Vegetables → Carrot, Celery, etc.

therefore:

Food → Apple, Orange, Carrot, Celery, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...