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.
I would like to be able to say something like Player.Team.opponent_week_1
How should I relate the models to each other? Player has_one team?
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.
I am using Ruby 2 and Rails 4. Thanks!
jackerman09,
As with many things in Rails, there's a few ways of going about it. @phgrey pointed out how to fix the players and teams.
Regarding opponent_week_1, 2, etc.:
I think the best way is if you actually do have a has_may :opponent_week
association from the Team model, like this:
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. 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. 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. 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
1. Players <=> Team
class Player < ActiveRecord::Base
...
belongs_to :team
...
end
class Team < ActiveRecord::Base
...
has_many :players
...
end
Be sure that migration create_players has field
t.references :team_id
2. Oppenents Youre lead the worsest way. Better take a look at HABTM (has_and_belongs_to_many) relations between commands
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.