我有以下Rails模型连接团队和用户:
class User < ActiveRecord::Base
has_many :memberships
has_many :teams, through: :memberships
end
class Team < ActiveRecord::Base
has_many :memberships
has_many :users
end
class Membership < ActiveRecord::Base
belongs_to :team
belongs_to :user
end
我想通过现有的会员资格表来实施团队经理。 在团队表中使用外键是否更好一点:
class Team < ActiveRecord::Base
belongs_to :manager_membership, class_name: 'Membership'
has_one :manager, through: :manager_membership, source: :user
# ...
end
或者在会员资格上添加一个额外的列(具有唯一索引)会更好:
class Team < ActiveRecord::Base
has_one :manager_membership, -> where { manager: true }, class_name: 'Membership'
has_one :manager, through: :manager_membership, source: :user
# ...
end
我想知道是否有外国人从团队到成员的双向关键并且回来是很奇怪的?或者它可能没有太大的区别?
答案 0 :(得分:0)
根据评论,您应该能够为您的用户和管理员使用single table inheritance。这意味着您可以在两个模型上使用相同的membership
关系。
class User < ActiveRecord::Base
has_many :memberships
has_many :teams, through: :memberships
end
class Manager < User
# your code
end
您现在可以在需要的地方使用Manager
,并直接在该模型上添加任何验证。如果您决定采用此路线,请务必在type
表格中添加User
列。
修改
再看一遍,你需要有一个单独的表来保持你的经理team and the actual team they manage clear. Your
团队之间的关系应该是这样的:
class Team < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
has_many :teams_managers
has_many :managers, through: :teams_managers
end
class Manager < User
has_many :teams_managers
# note here we're aliasing for clarity and specifying a source
has_many :managed_teams, through: :teams_managers, source: :team
end
# this is your association model for managers <-> teams
class TeamsManager < ActiveRecord::Base
belongs_to :manager
belongs_to :team
end
# so now you could call something like this
manager = Manager.find 1
manager.managed_teams =>[...]
manager.teams =>[...]
您还必须进行相应的迁移以实例化您的TeamsManagers
表。