class Profile
has_many :projects, :through => "teamss"
has_many :teams, :foreign_key => "member_id"
has_many :own_projects, :class_name => "Project", :foreign_key => :profile_id
has_many :own_teams, :through => :own_projects, :source => :teams
end
class Project
belongs_to :profile, :class_name => "Profile"
has_many :teams
has_many :members, :class_name => "Profile", :through => "teams", :foreign_key => "member_id"
end
class Team
belongs_to :member, :class_name => 'Profile'
belongs_to :project
end
我需要创建模型Evaluation
。我想做的是在页面project#view
为项目的每个成员(包括所有者)生成一个链接,以便进行Evaluation
此人将单击该链接并评估与此链接相关的人员。Project
的所有者将评估所有成员,所有成员将评估所有者。
我将模型Evaluation
定义为如下,但我认为我错过了一些东西:
class Evaluations < ActiveRecord::Base
belongs_to :evaluated, :class_name => 'Profile', :foreign_key => "evaluated_id"
belongs_to: :profile, :class_name => 'Profile', :foreign_key => "profile_id"
end
请记住,Evaluation
表将具有大量属性,这就是为什么我不打算使用has_many_and_belongs_to_many
。
如何创建此模型以执行我想做的事并能够通过project#show
页面满足我所需的一切?
谢谢!
编辑
完成的更改:
class Profile
has_many :evaluations, :dependent => :destroy, :foreign_key => :evaluation_id
has_many :evaluators, :through => :evaluations, :foreign_key => :profile_id
end
class Project
has_many :evaluations,:foreign_key => "project_id"
end
class Evaluations < ActiveRecord::Base
belongs_to :evaluated, :class_name => 'Profile', :foreign_key => "evaluated_id"
belongs_to: :profile, :class_name => 'Profile', :foreign_key => "profile_id"
belongs_to: :project, :class_name => 'Project', :foreign_key => "project_id"
end
您的团队和个人资料(成员)关联有点混乱。一个团队有许多配置文件(成员),一个配置文件(成员)属于一个团队。除此之外,您可能只是将事情过于复杂化。我很好奇你为什么不直接调用配置文件模型成员,让事情变得简单得多?
话虽如此,您正在执行一组非常复杂的关联。我强烈建议您仔细阅读 ActiveRecord 关联文档,以牢固地了解这些工作原理,尤其是主键和外键是如何自动确定的。
我想下面会得到你想要的。
class Team
has_and_belongs_to_many :members,
:class_name => "Profile"
belongs_to :project
belongs_to :team_leader,
:class_name => "Profile"
end
class Profile
has_and_belongs_to_many :teams
has_many :projects,
:through => :teams
has_many :owned_projects,
:class_name => "Project",
:foreign_key => "owner_id"
has_many :owned_teams,
:class_name => "Team",
:foreign_key => "team_leader_id"
has_many :evaluations
has_many :evaluations_given,
:class_name => "Evaluation",
:foreign_key => "evaluator_id"
end
class Project
has_many :teams
belongs_to :owner,
:class_name => "Profile"
has_many :members,
:through => :teams
has_many :evaluations
end
class Evaluation
belongs_to :profile
belongs_to :evaluator,
:class_name => "Profile",
:foreign_key => "evaluator_id"
belongs_to :project
end
支持这些模型定义的是以下表/键:
evaluation
id
profile_id
evaluator_id
project_id
teams
id
project_id
team_leader_id
profiles
id
project
id
owner_id
profiles_teams
profile_id
team_id
有了这个,您应该能够访问正确链接所需的集合/对象,例如:
项目成员
项目所有者
项目团队
团队.项目
简介.项目
profile.owned_projects
个人资料.团队
团队成员
团队负责人
项目评估
配置文件评估
评估.评估器
profile.evaluations_given
还要注意的是,如果你试图使用RESTFUL框架,你的嵌套资源将同样复杂。读起来!