Topic: question about has_many belongs_to association

I thought I had this figured out but I am having a problem...


#league model
has_many :score

#score model
belongs_to :league

#scores_controller
@scores = Score.find(:all, :conditions => [ "league_id = ?", @league_info.id,], :order => "date")
@league = @scores.build_league(params[:id])


I get undefinded method error for the build league line - what am I missing?

Re: question about has_many belongs_to association

I don't know if this is the reason for the error, but you are passing params[:id] here. Are you trying to assign the value of some attribute while building the league? The method is expecting a hash instead.

Railscasts - Free Ruby on Rails Screencasts

Re: question about has_many belongs_to association

In a relationship like this, the belongs_to model should be pluralized in the has_many declaration of the model that "owns" it:

#league model
has_many :scores
 
#score model
belongs_to :league

How is the build_league method defined? Does it expect a league id as an argument?

Last edited by gmacgregor (2007-01-27 02:25:07)

Re: question about has_many belongs_to association

Good catch gmacgregor. The :scores should be plural. That wouldn't have effected the build_league method though. This is generated by the "belongs_to" method and is the same as "League.new(...)" but automatically sets the @score.league_id to the value of the created league.

I see the problem now, here rburbach is fetching multiple scores with "find(:all)". The build_league method should be called on a single Score record. I'm not really sure what you are trying to do here with build_league actually.

Railscasts - Free Ruby on Rails Screencasts

Re: question about has_many belongs_to association

well the reason for making the assocition is because I want to display the league name that is associated with the score item. I am using the foreign key to reference the league table of course. I will need to do the same with my team table in order to display the team name rather than the team foreign key id...

Or is there a better way to do this?

Re: question about has_many belongs_to association

You can ignore this - it was due to me still grasping how these relationships work and not being familiar with the :class_name attribute I learned earlier, got things figured out now smile