Question

I have two models, Player and Team. Player belongs_to team, however, team does not have_many players because I am not concerned with having a list of the team's players. I am only making the association so that I can update a team's fields once (e.g. it's week_one_opponent) and have it pull to all of the players on that team.

My question is, from the player's new or edit forms, how can I set the player's team by providing the Team's name to the form? E.g. if player is 'Trent Richardson', who just got traded from the Browns to the Colts, I want to be able to go to his 'Edit' page and change the team field from 'Browns' to 'Colts'.

Thanks

Was it helpful?

Solution

Try this:

<%= form_for @player do |f| %>
<%= f.collection_select :team_id, Team.all, :id, :name, {}, { :multiple => false } %>
<% end %>

This assumes you have an attribute in your Team model called name. Make sure you add a team reference in the player's model.

If you are using Rails 3, you have to add :team_id to attr_accessible, if you are using Rails 4, you have to add :team_id to strong parameters in the user's controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top