[英]What type of relationship should these models have to each other?
I have two models: player and team. 我有两种模式:球员和团队。
A player has one team 球员有一支球队
Team has 5 fields on it (in addition to its name and location), opponent_week_1, opponent_week_2, etc. 队伍上有5个字段(除了其名称和位置外),对手_周_1,对手_周_2等。
I would like to be able to say something like Player.Team.opponent_week_1 我想说些类似Player.Team.opponent_week_1的话
How should I relate the models to each other? 我应该如何将模型彼此关联? Player has_one team? 玩家has_one球队?
How do I set the team's opponents? 如何设置球队的对手? I don't want the team to have_many opponents, because there will only be those 5, and I want to be able to say opponent_week_1, opponent_week_2, etc. 我不希望球队有很多对手,因为只会有5个对手,我希望能够说对手_week_1,对手_week_2等。
I am using Ruby 2 and Rails 4. Thanks! 我正在使用Ruby 2和Rails4。谢谢!
jackerman09, jackerman09,
As with many things in Rails, there's a few ways of going about it. 与Rails中的许多事情一样,有几种解决方法。 @phgrey pointed out how to fix the players and teams. @phgrey指出了如何修复球员和球队。
Regarding opponent_week_1, 2, etc.: 关于对手周1,2等:
I think the best way is if you actually do have a has_may :opponent_week
association from the Team model, like this: 我认为最好的办法是,如果你实际做有has_may :opponent_week
从小组模型关联,就像这样:
class Team < ActiveRecord::Base
...
has_many :fields
...
end
You'd then have to limit insertion of opponent weeks to each Team to only 5 through validations and/or through the forms. 然后,您必须通过验证和/或通过表格将每个团队的对手周插入限制为只有5周。 Since users will be entering those opponent weeks through forms, that would be an easy way to go about it at first. 由于用户将通过表格输入对手周数,因此一开始这将是一种简单的方法。 You have control of the forms, so just limit how many opponent_weeks they put in for each Team through forms. 您可以控制表格,因此只需限制他们通过表格为每个团队投入的对手周数。
How you'd go about about calling them opponent_week_1
, opponent_week_2
etc.: there are a few ways. 称呼他们为“ opponent_week_1
,“ opponent_week_2
等的方式:有几种方法。 I would try putting aa method_missing
method in your model (google to see how to do it) then parse the name of the method that you called. 我会尝试在您的模型中放入一个method_missing
方法(谷歌看如何做),然后解析您调用的方法的名称。 Something like this: 像这样:
def method_missing( method_name )
if method_name.starts_with?( "opponent_week_" )
# get the number at the end, then call
opponent_weeks[ num_of_week - 1 ]
else
super
end
end
All the best and let me know if you need clarifications. 最好的,如果需要澄清,请告诉我。
Take a look here - http://guides.rubyonrails.org/association_basics.html 在这里看看-http: //guides.rubyonrails.org/association_basics.html
1. Players <=> Team 1.玩家<=>团队
class Player < ActiveRecord::Base
...
belongs_to :team
...
end
class Team < ActiveRecord::Base
...
has_many :players
...
end
Be sure that migration create_players has field 确保迁移create_players具有字段
t.references :team_id
2. Oppenents Youre lead the worsest way. 2.对手你是最糟糕的领导者。 Better take a look at HABTM (has_and_belongs_to_many) relations between commands 更好地了解命令之间的HABTM(has_and_belongs_to_many)关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.