这感觉应该很明显;对不起,如果是。如何使用我在Rails中创建的关联?
我在导轨上创建了两个脚手架:Teams
和Players
。得到这个工作没有问题。我想将它们链接起来,因为Team
有很多Players
和Players
属于Team
。于是我进入了各自的模型并创建了这个协会。我四处看了一眼,看到我不得不在Players
中创建一个新列以容纳外键,所以我通过迁移来实现这一点;我将其称为team_id
,并更新了我创建的5个记录中的4个,以提供ID为1
。基本上,什么this answer指示。
现在我不明白的是,我该如何使用该关联?因此,为了得到一个具体的例子,我将如何根据该团队的ID列出Team
的show.html.erb模型中的所有Players
?不知怎的,我需要在我的控制器中拨打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 %>
酷!感谢那个资源。得到它与@team而不是团队合作。它是如何找到'team_id'的?如果我把它称为别的东西,它会猜到右列是外键吗? – Brendan 2013-03-03 18:40:44
不,它不会工作。它猜测来自关联名称的外键名称。您可以选择自定义外键。顺便说一句,在迁移中,你可以使用't.references:team',而不是't.integer:user_id',这是一回事。 – Robin 2013-03-03 18:50:19
很酷。非常感谢你的帮助! – Brendan 2013-03-03 18:53:51