0

这感觉应该很明显;抱歉,如果是的话。

我在 rails 中创建了两个脚手架:TeamsPlayers. 得到那个工作没问题。不过,我想将它们链接起来,因为 aTeam有很多Players并且Players属于 a Team。所以我进入了各自的模型并创建了关联。我四处阅读,发现我必须在其中创建一个新列Players来容纳外键,所以我通过迁移来做到这一点;我调用它team_id并更新了我创建的 5 条记录中的 4 条,以提供1. 基本上,这个答案说明了什么。

我现在不明白的是,我该如何使用该关联?那么,为了获得一个具体的例子,我将如何根据该团队的 ID列出所有Playersin的 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 %>
4

1 回答 1

1

您可能想在这里阅读文档:http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

您可以通过以下方式访问玩家的团队:

player.team

您可以通过以下方式访问球队的球员:

team.players

然后在视图中遍历这些玩家

team.players.each do |player|

end

belongs_to您在模型中调用的类方法has_many将为您生成方法。

例如,belongs_to :team将生成:team, team=(team), build_team(attributes),create_team(attributes)等...

于 2013-03-03T18:34:42.867 回答