0

I have a fixtures and a teams database to show football fixtures. I can currently view all fixtures(index & show..) and all teams(index only).

create_table "fixtures", :force => true do |t|
    t.integer  "home_id"
    t.integer  "away_id"
    t.date     "date"
    ...

  create_table "teams", :force => true do |t|
    t.string   "name"
    ...

My Fixture & Team models are below;

class Fixture < ActiveRecord::Base
  belongs_to :home, :class_name => 'Team'
  belongs_to :away, :class_name => 'Team'
  ...
class Team < ActiveRecord::Base
  has_many :fixtures
  ...

I get the following error when trying to display a teams fixtures on 'teams#show' page

Processing by TeamsController#show as HTML
  Parameters: {"id"=>"3"}
  Team Load (0.4ms)  SELECT "teams".* FROM "teams" WHERE ("teams"."id" = 3) LIMIT 1
  Fixture Load (0.3ms)  SELECT "fixtures".* FROM "fixtures"
  Fixture Load (0.3ms)  SELECT "fixtures".* FROM "fixtures" WHERE ("fixtures".team_id = 3)
SQLite3::SQLException: no such column: fixtures.team_id: SELECT "fixtures".* FROM "fixtures" WHERE ("fixtures".team_id = 3)

I understand the error is saying it's looking for team_id in the fixtures but that doesn't exist as I have a home_id and away_id as each fixture always contains two teams, so how do I build a find to display an individual teams fixtures?

raphael_turtle
  • 7,154
  • 10
  • 55
  • 89

1 Answers1

0

I wish there was a good way of doing this too, but there really isn't. Probably the best workarounds are:

  1. To have two has_manys, :home_fixtures and :away_fixtures, and then a method fixtures that returns the union of the two (see this question for more details).
  2. To skip out on the has_manys altogether and just write a method fixtures that gives you what you want without actually having and ActiveRecord relationship set up.

Like so (Rails 2.3-Style):

def fixtures
    return Fixture.all(:conditions => ['away_id = :id OR home_id = :id', {:id => self.id}])
end

Hope this helps!

Community
  • 1
  • 1
Xavier Holt
  • 14,471
  • 4
  • 43
  • 56
  • I don't think I understand the first way, I got a private method error using the 2nd. In my teams controller I have def show @team = Team.find(params[:id]) @fixtures = Fixture.all(:conditions => ['away_id = :id OR home_id = :id', {:id => @team.id}]) end ... I got it working by changing self.id to @team.id – raphael_turtle Feb 08 '11 at 13:50
  • @raphael_turtle I had envisioned the method going into the Team model, but I guess I forgot to mention that. Sorry - glad you got it working anyway! – Xavier Holt Feb 08 '11 at 19:57