Rails 关联设计,has_many 通过
Rails association design, has_many through
我正在开发一个虚拟 rails 应用程序;作为我的编程技能自学的一部分。而且我觉得 rails 关联概念有点卡住了,因为我不确定哪种方法是正确的。
在这个练习中我想要以下模型:
- 用户
- 项目
- 团队
我想创建以下关联:
- User
有很多 Project
- Project
有许多 User
到 Team
- Team
有许多 User
到 Project
想法是用户可以创建项目并加入或邀请其他用户。在保存项目之前,感谢 before_create
,应用程序将创建一个新团队 Project_Team
,其中包含 User
和他在项目创建过程中添加的其他用户。
当然,我不是在谈论模型依赖性,因为一旦我设置了正确的关联,我就会解决这一点。
我写了下面的代码,但我无法得到上面解释的关联,以按预期工作:
class User < ActiveRecord::Base
has_many :project
has_many :team, through :project
end
class Project < ActiveRecord::Base
has_one :team
has_many :user, through :team
end
class Team < ActiveRecord::Base
belongs_to :project
has_many :user, through :project
end
非常感谢您以后的帮助(以及对上述 "might-be" 错误代码的容忍度)。
干杯
您必须使 has_many
关联复数,但保持 belongs_to
单数。 through
之后还缺少冒号。你的联想应该是:
class User < ActiveRecord::Base
has_many :projects
has_many :teams, through: :projects
end
class Project < ActiveRecord::Base
has_one :team
has_many :users, through: :team
end
class Team < ActiveRecord::Base
belongs_to :project
has_many :users, through: :project
end
查看 Rails guides 了解更多信息。
我正在开发一个虚拟 rails 应用程序;作为我的编程技能自学的一部分。而且我觉得 rails 关联概念有点卡住了,因为我不确定哪种方法是正确的。
在这个练习中我想要以下模型:
- 用户
- 项目
- 团队
我想创建以下关联:
- User
有很多 Project
- Project
有许多 User
到 Team
- Team
有许多 User
到 Project
想法是用户可以创建项目并加入或邀请其他用户。在保存项目之前,感谢 before_create
,应用程序将创建一个新团队 Project_Team
,其中包含 User
和他在项目创建过程中添加的其他用户。
当然,我不是在谈论模型依赖性,因为一旦我设置了正确的关联,我就会解决这一点。
我写了下面的代码,但我无法得到上面解释的关联,以按预期工作:
class User < ActiveRecord::Base
has_many :project
has_many :team, through :project
end
class Project < ActiveRecord::Base
has_one :team
has_many :user, through :team
end
class Team < ActiveRecord::Base
belongs_to :project
has_many :user, through :project
end
非常感谢您以后的帮助(以及对上述 "might-be" 错误代码的容忍度)。
干杯
您必须使 has_many
关联复数,但保持 belongs_to
单数。 through
之后还缺少冒号。你的联想应该是:
class User < ActiveRecord::Base
has_many :projects
has_many :teams, through: :projects
end
class Project < ActiveRecord::Base
has_one :team
has_many :users, through: :team
end
class Team < ActiveRecord::Base
belongs_to :project
has_many :users, through: :project
end
查看 Rails guides 了解更多信息。