2016-04-03 131 views
0

我有3種型號(用戶,球隊和聯盟),我想在它們之間建立以下關係:問題Ruby on Rails中建模與ActiveRecord的關係數據庫

  • 用戶可以擁有多個團隊。
  • 聯盟由多個團隊組成,它由用戶擁有。
  • 一個團隊同時屬於一個用戶和一個聯盟。

我是Ruby on Rails的新手,我似乎無法弄清楚如何表示這些關係。當我嘗試測試模型時,由於我不知道如何從用戶和聯盟同時建立一個團隊,因此在實例化團隊時出現錯誤。任何幫助將非常感謝,事先感謝。

回答

0

型號:

class User < ActiveRecord::Base 
    has_many :teams 
end 

class League < ActiveRecord::Base 
    belongs_to :user 
    has_many :teams 
end 

class Team < ActiveRecord::Base 
    belongs_to :league 
    belongs_to :user 
end 

遷移:

create_table(:users) do |t| 
    t.string :name 
    t.timestamps 
end 

create_table(:leagues) do |t| 
    t.references :user, index: true 
    t.string :name 
    t.timestamps 
end 

create_table(:teams) do |t| 
    t.references :league, index: true 
    t.references :user, index: true 
    t.string :name 
    t.timestamps 
end 

我建議在Rails的指南,瞭解associationsmigrations

+0

感謝您的幫助!顯然,我在做一個無關的錯誤來運行我的測試,導致我相信我的模型彼此之間存在着某種問題。 –