2013-03-03 27 views
0

這感覺應該很明顯;對不起,如果是。如何使用我在Rails中創建的關聯?

我在導軌上創建了兩個腳手架:TeamsPlayers。得到這個工作沒有問題。我想將它們鏈接起來,因爲Team有很多PlayersPlayers屬於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 %> 

回答

1

您可能需要閱讀的文檔在這裏:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

您可以通過訪問該球員的球隊:

player.team 

你可以訪問該球隊的球員:

team.players 

然後在視圖中迭代這些播放器

team.players.each do |player| 

end 

您在模型中調用的類方法(如belongs_tohas_many)將爲您生成方法。

例如,belongs_to :team將產生:teamteam=(team)build_team(attributes)create_team(attributes)等等

+0

酷!感謝那個資源。得到它與@team而不是團隊合作。它是如何找到'team_id'的?如果我把它稱爲別的東西,它會猜到右列是外鍵嗎? – Brendan 2013-03-03 18:40:44

+1

不,它不會工作。它猜測來自關聯名稱的外鍵名稱。您可以選擇自定義外鍵。順便說一句,在遷移中,你可以使用't.references:team',而不是't.integer:user_id',這是一回事。 – Robin 2013-03-03 18:50:19

+0

很酷。非常感謝你的幫助! – Brendan 2013-03-03 18:53:51

相關問題