cant use Activerecord find method with associations
here are 开发者_运维百科my models:
#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
When i execute Game.find_games("real") i get : ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: team_1.name
How can i fix the problem i thought that using :include would fix the problem.
Team_1 is not the name of the table. The conditions don't work with associations as defined in ruby, but with the tables themselves. The condition should state: :conditions => ["teams.name = ?", name]
Also, I don't think the teams class is correct, you certainly can't define games twice, and the foreign keys should be the same as the belongs to:
#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
There is a much better way to do that, but I can't remember it off the top of my head.
精彩评论