Rails:多个多对多关系(两个以上)

Rails: Multiple many-to-many relationships (more than two)

Rails这里是新手。

在将模型从 Django 移植到 Rails 时,我对寻找最佳关系感到困惑...

我要实现的模型:

是否可以与 has_many 建立关联:通过或更好地使用 has_and_belongs_to?

我认为 :through 关联会很复杂,因为给定模型有两个以上的交叉关系。

我可以看到两种建立关系的方式:一种大连接模型或小连接模型,适用于所有当前模型之间的多对多关系。

class Role
  has_many :relations
  has_many :users, through: :relations
  has_many :teams, through: :relations
end

class User
  has_many :relations
  has_many :roles, through: :relations
  has_many :software, through: :relations
end

class Team
  has_many :relations
  has_many :software, through: :relations
end

class Software
  has_many :relations
  has_many :users, through: :relations
  has_one :team
end

class Relation
  belongs_to :user
  belongs_to :role
  belongs_to :teams
  belongs_to :software
end

has_many :through 为您提供了拥有功能齐全的连接模型的额外灵活性 class。如果您想要对关系的某些方面进行建模,而不仅仅是两个事物相互关联这一简单事实,则需要这样做。

据我所知,has_many :through 没有任何缺点,除了您的代码库可能会大一两行,而且还有很多优点。我会一直使用 has_many: through

re 关联很复杂:在进行任何编码之前,用纸和铅笔(或者如果您愿意,也可以使用 UML 绘图应用程序)将它们全部画出来。如果您以前有一个可用的 Django 应用程序,那么它应该足够简单来映射模式:它们都是对象关系系统。