2012-01-31 34 views
0

我嘗試使用軌道構建足球經理遊戲,並且我與軌道關聯卡住了。在軌道中使用多個連接找到

team table 
    ... 

history table 
    team_id 
    saison_id 

saison table 
    league_id 
    league table 
    ... 

我想找一個聯盟的所有球隊。

class History < ActiveRecord::Base 
    belongs_to :saison 
    belongs_to :team 
end 

class Saison < ActiveRecord::Base 
    has_many :histories 
    has_many :teams, :through => :histories 
    belongs_to :league 
end 

class League < ActiveRecord::Base 
    has_many :saisons 
end 

class Team < ActiveRecord::Bases 
    has_many :histories 
    has_many :saisons, :through => :histories 
end 

我要像做(在聯賽控制器的顯示方法):

@team = Team.find(:all, :include => [:saisons => :histories, :leagues => :saisons], 
      :conditions => ["leagues.id = ?", params[:id]]) 

,但它不工作。

SQL查詢:

SELECT Team.* 
FROM Team, Saison, History, League 
WHERE History.Team_ID = Team.ID AND 
     History.Saison_ID = Saison.ID AND 
     Saison.League_ID = League.ID 

該查詢返回所有球隊一個賽鬆...但我不實現,使之成爲聯賽

@division = Team.find(:all, :include => [:saisons => :histories], 
           :conditions =>["saisons.id =?",params[:id]]) 

回答

0

在聯賽控制器,在表演方法,我嘗試像

@team = Equipe.find(:all, :include => [:saisons => :history], 
           :conditions =>["saisons.league_id =?",params[:id]]) 

我將包括在查找聲明聯賽有同樣的結果選項卡中的所有屬性(名稱爲實例)。

我知道我可以在另一個查詢中瞭解聯盟的信息,但這不是最好的方式。

0

工作,我不知道你如何到達這一點,但你的命名約定是錯誤的Rails應用程序。

讓我們看看歷史。 你的模型應該被稱爲「歷史」。
應用程序/模型的第一線/ history.rb是:
class History < ActiveRecord::Base

在數據庫中生成的表應該被稱爲「歷史」。

然後當你建立你的關聯時,你需要注意多元化。

has_many後面總是跟着一個複數詞。
belongs_to總是跟着一個單數的單詞。

的賽鬆協會應該是這樣的:

class Saison < ActiveRecord::Base 
    has_many :histories 
    has_many :teams, :through => :histories 
    belongs_to :league 
end 

希望這有助於。

+0

我的數據庫是用法語提出的,我用英文翻譯了一些字段,但似乎我犯了翻譯錯誤。我編輯關於你所說的話的線程。謝謝 – psic 2012-01-31 21:16:24

1

如果你用另一種語言命名你的表和模型,那麼你很可能不會遵循Rails的命名約定(但它也可能發生在英語上!)。

無論如何,如果某個單詞的複數不是以S結尾,那麼您必須轉到位於your_app/config/initializers的文件inflections.rb並在其中添加複數個特定單詞。這只是一個例子:

ActiveSupport::Inflector.inflections do |inflect| 
    inflect.irregular 'merchandise', 'merchandising' 
end 

至於你的問題,我不知道我是否理解,但你想要一個賽季的所有球隊?這很簡單,它只是:

@saison_teams = saison.teams 

然後,你想一個部門的所有球隊,但你還沒有告訴我們一個部門是什麼!

+0

OH ...我想要一個聯盟的所有球隊 – psic 2012-01-31 22:19:24

+0

那麼,你可以像這樣迭代球隊,但它不是很有效率:'League.saisons.each do | saison |把saison.teams結束' – Ashitaka 2012-01-31 22:36:00

+0

是的,但我寧願使用和找到最好的:包括聲明,以獲得我的ifnd聲明中的聯賽和saison之間的聯接,爲了學習 – psic 2012-01-31 22:45:26