我很难让:association
助手工作。基本上我想要一个包含所有 32 个团队的选择框,而不是一个无用的:team_id
数字,我想使用 ActiveRecord 魔术来显示来自相应团队的“缩写”或“城市”。我正在使用 MySQL DB 顺便说一句。
楷模
class Player < ActiveRecord::Base
belongs_to :teams
end
class Team < ActiveRecord::Base
has_many :players
end
控制器
@player = Player.find(params[:id])
看法
<%= simple_form_for @player do |f| %>
<%= f.input :first %>
<%= f.input :last %>
<%= f.association :teams %>
<%= f.button :submit %>
<% end %>
===================
只是为了帮助可视化这里的数据,是数据在数据库中出现的样本。
数据库 - 团队
+----+-----------+-----------+---------------------+---------------------+------+
| id | city | name | created_at | updated_at | abbr |
+----+-----------+-----------+---------------------+---------------------+------+
| 1 | Arizona | Cardinals | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | ARI |
| 2 | Atlanta | Falcons | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | ATL |
| 3 | Baltimore | Ravens | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | BAL |
| 4 | Buffalo | Bills | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | BUF |
+----+-----------+-----------+---------------------+---------------------+------+
数据库 - 玩家
+----+---------+----------+--------+-----------------+---------------------+---------------------+
| id | team_id | position | first | last | created_at | updated_at |
+----+---------+----------+--------+-----------------+---------------------+---------------------+
| 1 | 5 | QB | Derek | Anderson | 2013-08-26 18:48:59 | 2013-08-27 20:41:37 |
| 2 | 24 | QB | Matt | Barkley | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
| 3 | 18 | QB | McLeod | Bethel-Thompson | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
| 4 | 6 | QB | Matt | Blanchard | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
| 5 | 26 | QB | Sam | Bradford | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
+----+---------+----------+--------+-----------------+---------------------+---------------------+