在Rails中具有has_and_belongs_to_many [英] has_and_belongs_to_many in Rails

查看:114
本文介绍了在Rails中具有has_and_belongs_to_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails中使用has_and_belongs_to_many关联而不是has_many:through有明显的错误吗?我知道这些 文章

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?

有想法吗?

推荐答案

has_and_belongs_to_many用于简单的多对多关系.

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

has_many:through是用于间接的一对多关系或具有属性的多对多关系.

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

如果您只是在寻找简单的多对多关系,我看不出有任何理由不使用has_and_belongs_to_many.

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.

多对多关系示例:

用户属于零个或多个组,并且该组具有零个或多个成员(用户).

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

与属性的多对多示例:

用户属于零个或多个组,并且该组具有零个或多个具有等级的成员.

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

例如,爱丽丝可能是组A中的管理员,并且是组B中的主持人.您可以在连接表中保留此属性.

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.

间接一对多关系示例:

一个类别包含零个或多个子类别,每个子类别包含零个或多个项目.

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.

考虑以下类别:

食物→水果,蔬菜
水果→苹果,橙子等.
蔬菜→胡萝卜,芹菜等

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

因此:

食物→苹果,橙子,胡萝卜,芹菜等

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

这篇关于在Rails中具有has_and_belongs_to_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆