views:

45

answers:

1

I want to create a list from a class' attributes

I'm new with ruby- i have an activerecord class called fixture and what an array of "Home Team", "Draw", "Away team", where home team and away team are both fields in the Fixture table

I have come up with the following code sticking it in the Fixture class- how do access the values of the class?

self.fix_list = [home_team.title, "Draw", away_team.title]
A: 

I think that "Fixture" is a pretty bad name for a model. Anyways:

class Fixture < ActiveRecord::Base
  belongs_to :home_team, :class_name => "Team", :foreign_key => "home_team_id"
  belongs_to :away_team, :class_name => "Team", :foreign_key => "away_team_id"
  named_scope :with_team, lambda { |team_id| { :conditions => ['(home_team_id = ? 
    or away_team_id = ?)', team_id, team_id]} }

  def fix_list
    [home_team.title, "Draw", away_team.title]
  end
end

class Team < ActiveRecord:Base
  def fixtures
    Fixture.with_team(id)
  end
end

Of course, in your migration for the "fixtures" table, you need to create the columns named home_team_id and away_team_id.

Edit: I just notices that my initial has_many association in Team is useless. That named_scope is untested and I'm going to bed now!

cite
Yes, someone pointed it out to me before but no problems have arisen so far, thanks for that
chris
Please note that I edited the above posting - I was tired, so I used symbol names in the class and foreign key names, which is wrong.
cite