假设我想创建一个完成编码项目,开发人员及其角色的数据库。
模型看起来像这样:
project has_and_belongs_to_many developers
developers has_and_belongs_to_many projects
developers_projects表如下所示:
int: developer_id, project_id
string: role
让我知道我有3个开发人员和2个项目,其ID和名称分别为
1, Ashley
2, Bob
3, Charles
1, Tic Tac Toe
2, Snake
他们的实际角色是
Project 1:
- Manager: Ashley
- Coder: Bob, Charles
Project 2:
- Manager: Charles
- Coder: Ashley
是否可以在项目下定义经理和编码器对象?
像:
class Project < ActiveRecord::Base
has_and_belongs_to_many :developers
has_and_belongs_to_many :managers, :class_name => "developers", :condition => "role = 'manager'"
has_and_belongs_to_many :coders, :class_name => "developers", :condition => "role = 'coder'"
end
(这不起作用)
提前谢谢你,
答案 0 :(得分:2)
has_and_belongs_to_many
允许在不声明模型的情况下创建连接表。至于你想在这个表中拥有属性,你应该创建单独的模型,例如,你的案例中的ProjectRoles:
class ProjectRole < ActiveRecord::Base
belongs_to :developer
belongs_to :project
attr_accessible :role
end
class Project < ActiveRecord::Base
has_many :manager_roles, :class_name => "ProjectRole",
:conditions => { :role => 'manager' }
has_many :managers, :through => manager_roles
end
class Developer < ActiveRecord::Base
has_many :project_roles
has_many :projects, :through => project_roles
end