【发布时间】:2014-08-09 00:04:59
【问题描述】:
我有这个具有以下关联的用户和团队模型:
用户.rb
class User < ActiveRecord::Base
belongs_to :team
team.rb
class Team < ActiveRecord::Base
has_many :users
has_one :leader, class_name: "User", foreign_key: "leader_id"
belongs_to :manager, class_name: "User", foreign_key: "manager_id"
但我似乎无法想象将其正确地表示为迁移。起初,我是这样做的:
class AddTeamIdToUsers < ActiveRecord::Migration
def change
add_column :users, :team_id, :integer
add_index :users, :team_id
end
end
class AddUsersToTeams < ActiveRecord::Migration
def change
add_reference :teams, :leader, index: true
add_reference :teams, :manager, index: true
end
end
当然,我在AddTeamToIdUsers 上所做的是多对一关联,因为Team 可以有多个Users,但领导职位 应该只是仅限特定团队(成员也是如此,他们不应该属于其他团队)。但是,经理可以拥有许多团队来管理。回到我的关注点,我如何将我的场景表示为迁移?或者我应该在我的协会中做出任何调整?在考虑了必要的调整和解决方案后,应用程序是否会在添加/更新团队时自动遵循关联规则?
【问题讨论】:
-
如果用户管理一个团队,他们是否被称为该团队的“一部分”,即他们会被包含在
team.users中吗?领导呢? -
你的两个答案都是肯定的。 leader 和 manager 都是用户属性 type 的值(默认为 worker)。
-
领导者或工人是否也可以是团队的经理,即一个用户可以有多种类型?
标签: ruby-on-rails ruby activerecord associations rails-migrations