[英]Rails association design, has_many through
I am working on a dummy rails application; 我正在研究虚拟Rails应用程序; as part of my programming skills self education. 作为我的编程技能自我教育的一部分。 And I am feeling a bit stuck with the rails association concept as I am not sure which is the right way to go for. 我不确定Rails协会的概念,因为我不确定这是正确的方法。
In this exercise I want to have the following models: 在本练习中,我希望具有以下模型:
- User -用户
- Project -项目
- Team -团队
And I would like to create the following associations: - User
has many Project
我想创建以下关联:- User
有很多Project
- Project
has many User
through Team
- Project
通过Team
拥有许多User
- Team
has many User
through Project
- Team
通过Project
拥有许多User
The idea is that a user can create a project and on-board or invite other users. 这个想法是,一个用户可以创建一个项目并加入或邀请其他用户。 Before the project get saved, thanks to a before_create
, the application will create a new team Project_Team
with the User
and the other users he added during the Project creation process. 在保存项目之前,由于使用了before_create
,应用程序将与该User
以及在项目创建过程中添加的其他用户一起创建一个新团队Project_Team
。
Of course I am not talking about model dependencies as i will tackle this point once I have the right associations set. 当然,我并不是在谈论模型依赖性,因为一旦设置了正确的关联,我将解决这一点。
I wrote the following code but I could not get the association, explained above, to working as expected: 我编写了以下代码,但如上所述无法使关联按预期工作:
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
Many thanks for your future help (and tolerance for the "might-be" bad code above). 非常感谢您将来提供的帮助(以及对上面“可能”糟糕的代码的容忍度)。
Cheers 干杯
You have to pluralize has_many
associations but keep your belongs_to
singular. 您必须对has_many
关联进行复数处理,但必须将自己的belongs_to
数保持为单数。 You're also missing colons after the through
. through
后您也缺少冒号。 Your associations should be: 您的关联应为:
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
Check out the Rails guides for more info. 查看Rails指南以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.