无法使用Activerecord查找具有关联的方法

时间:2010-05-04 20:59:50

标签: ruby-on-rails ruby 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会解决问题。

1 个答案:

答案 0 :(得分: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

有一种更好的方法可以做到这一点,但我记不起来了。