Rails中通过关系2转1 has_many(如何将三个模型连接在一起)
连接以下三个模型的最佳方式是什么?
class Tournament < ActiveRecord::Base
has_many :submissions
has_many :creatures, :through => :submissions, :uniq => true
has_many :teams, :through => :submissions, :uniq => true
end
class Creature < ActiveRecord::Base
belongs_to :team
has_many :tournaments, :through => :team
end
class Submission < ActiveRecord::Base
belongs_to :tournament
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :creatures
has_many :submissions
has_many :tournaments, :through => :submissions
end
我想要实现这样的目标:
> team_1.tournaments[0] = tournament_1
> tournament_1.teams[0]
(returns team_1)
> team_1.tournaments[0].creatures
(returns [])
> team.tournaments[0].creatures[0] = creature_1
> creature_1.tournaments
(returns tournament_1)
让特定生物和团队与特定锦标赛相关联的最有效方法是什么?
编辑:以上是期望的行为..当前的问题是,一旦我将团队添加到tournament.teams中,该团队中的所有生物都会自动将该锦标赛列在creature.tournament中,而我正在尝试使生物有选择地添加到锦标赛中。一张连接表是否有可能?
谢谢!
What would be the best way to connect following three models?
class Tournament < ActiveRecord::Base
has_many :submissions
has_many :creatures, :through => :submissions, :uniq => true
has_many :teams, :through => :submissions, :uniq => true
end
class Creature < ActiveRecord::Base
belongs_to :team
has_many :tournaments, :through => :team
end
class Submission < ActiveRecord::Base
belongs_to :tournament
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :creatures
has_many :submissions
has_many :tournaments, :through => :submissions
end
I want to achieve something like this:
> team_1.tournaments[0] = tournament_1
> tournament_1.teams[0]
(returns team_1)
> team_1.tournaments[0].creatures
(returns [])
> team.tournaments[0].creatures[0] = creature_1
> creature_1.tournaments
(returns tournament_1)
What is the most efficient way to have a specific creature and a team associated with a specific tournament?
EDIT: The above is the desired behavior.. Current problem is that as soon as I add team to tournament.teams all the creatures in that team automatically have that tournament listed in creature.tournament, while I am trying to make it so that creatures are added to tournament selectively.. Is it at all possible with one join table?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
提交应该是
锦标赛
和团队
之间的连接表,对吗?模型关系:
现在您应该能够调用:
team_1.tournaments[0].creatures
Submission should be your join table between
Tournaments
andTeams
, correct?Model relationships:
Now you should be able to call:
team_1.tournaments[0].creatures