【发布时间】:2016-02-09 13:21:48
【问题描述】:
Rails 新手在这里。
在将模型从 Django 移植到 Rails 时,我对寻找最佳关系感到困惑......
我想实现的模型:
- 角色(有很多用户和团队)
- 用户(拥有许多角色和软件)
- 软件(有很多用户和一个团队)
- 团队(拥有许多软件和文档)
- 补丁(有很多团队和软件)
- 文档(包含许多团队和软件)
是否可以通过或更好地使用 has_and_belongs_to 与 has_many: 建立关联?
我认为:通过关联会很复杂,因为给定模型有两个以上的交叉关系。
我可以看到两种建立关系的方式:一种大连接模型或小连接模型,用于当前所有模型之间的多对多关系。
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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 many-to-many