这感觉应该很明显;抱歉,如果是的话。
我在 rails 中创建了两个脚手架:Teams
和Players
. 得到那个工作没问题。不过,我想将它们链接起来,因为 aTeam
有很多Players
并且Players
属于 a Team
。所以我进入了各自的模型并创建了关联。我四处阅读,发现我必须在其中创建一个新列Players
来容纳外键,所以我通过迁移来做到这一点;我调用它team_id
并更新了我创建的 5 条记录中的 4 条,以提供1
. 基本上,这个答案说明了什么。
我现在不明白的是,我该如何使用该关联?那么,为了获得一个具体的例子,我将如何根据该团队的 ID列出所有Players
in的 show.html.erb 模型?Team
我需要以Players
某种方式调用我的控制器吗?
架构:
ActiveRecord::Schema.define(:version => 20130303052538) do
create_table "players", :force => true do |t|
t.string "position"
t.integer "number"
t.integer "grade"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "first_name"
t.string "middle_name"
t.string "last_name"
t.integer "team_id"
end
create_table "teams", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
模型(为简洁起见,将它们集中在一起):
class Player < ActiveRecord::Base
attr_accessible :grade, :first_name, :middle_name, :last_name, :number, :position, :team_id
# Relationships
belongs_to :team
end
class Team < ActiveRecord::Base
attr_accessible :name
# Relationships
has_many :players
end
我的Team
控制器的一部分:
class TeamsController < ApplicationController
def show
@team = Team.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @team }
end
end
end
看法:
<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= @team.name %>
<%= @team.id %>
</p>
<p>
<b>Players:</b>
# I want to list them here.
</p>
<%= link_to 'Edit', edit_team_path(@team) %> |
<%= link_to 'Back', teams_path %>