2010-05-04 41 views
0

這裏是我的模型:不能使用ActiveRecord找到方法與各協會

#game 
class Game < ActiveRecord::Base 
    #relationships with the teams for a given game 
    belongs_to :team_1,:class_name=>"Team",:foreign_key=>"team_1_id" 
    belongs_to :team_2,:class_name=>"Team",:foreign_key=>"team_2_id" 

    def self.find_games(name) 
    items = Game.find(:all,:include=>[:team_1,:team_2] , :conditions => ["team_1.name = ?", name])  
    end 
end 

#teams 
class Team < ActiveRecord::Base 
    #relationships with games 
    has_many :games, :foreign_key =>'team_1' 
    has_many :games, :foreign_key =>'team_2' 
end 

當我執行Game.find_games( 「真實」)我得到: 的ActiveRecord :: StatementInvalid:SQLite3的::的SQLException:沒有這樣的列:team_1.name

我該如何解決我認爲使用的問題:include會解決問題。

回答

0

Team_1不是表格的名稱。條件不適用於ruby中定義的關聯,但與表本身一起使用。該條件應說明::conditions => ["teams.name = ?", name]

另外,我不認爲球隊的類是正確的,你當然不能定義遊戲兩次,外鍵應該是一樣屬於:

#teams 
class Team < ActiveRecord::Base 
    #relationships with games 
    has_many :team_1_games, :class_name => "Game", :foreign_key =>'team_1_id' 
    has_many :team_2_games, :class_name => "Game", :foreign_key =>'team_2_id' 
end 

有一個更好的方法來做到這一點,但我不記得它的頭頂。

+0

我試過它的工作,但它只在team_1.I中尋找一個名稱,我希望它找到屬性team_1和team_2。 – fenec 2010-05-04 22:54:11