0

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

4

1 回答 1

2

尝试这个:

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

这假设您的团队模型中有一个名为name. 确保在玩家模型中添加团队引用。

如果您使用的是 Rails 3,则必须添加:team_idto attr_accessible,如果您使用的是 Rails 4,则必须添加:team_id到用户控制器中的强参数。

于 2013-09-21T16:04:45.520 回答