Harold Hausman wrote: > I have two tables in my DB, one which keeps track of teams and another > which keeps track of matches. (two teams can play a match and there is > one winner and one loser) The difficult bit seems to be that the > team's id can be stored in either one of two columns in the matches > table. > > I feel like I should be able to setup the Team model to have a > collection of the matches which that team has participated in and > here's what I've tried so far: > > class Team < ActiveRecord::Base > has_many :matchess, :finder_sql => > "select * from matches " + > "where matches.one = #{id} " + > "or matches.two = #{id}" > end > > Now this 'works' but it seems that the id that it is inserting into > the SQL string is the ruby unique id for the Team object that is > created. What I want is the id of the team which is stored in the > database. Is this stored in the Team object anywhere? or am I going at > this all backwards? I haven't used this particular feature of Rails, but I think what you want is to use single quotes around the SQL snippets rather than double quotes. Double quotes evaluate #{expressions like this} as soon as they're created, while ActiveRecord wants to evaluate it later once it has a Team object to get the id from. > > Is there a resource somewhere that explains when you should use > has_many vs belongs_to or has_and_belongs_to_many? I thought there was, but I can't find it. The difference is basically this: X belongs_to Ys: Every X record has a y_id entry identifying which Y it belongs to. Y has_many Xs: Has a method that will return all Xs with a y_id equal to its own. (Basically, objects that belong to another keep track of their owner. Telling the owner that it owns them gives it the ability to automatically find them.) X has_and_belongs_to_many Ys: This one works differently. Every X can refer to several Ys, and every Y can refer to several Xs. To do this, you create a join table where each row represents a relationship between an X and a Y. This might be a good choice for the relationship between Matches and Teams, because each team can have many matches and each match has many teams.