Has_many relationships - use variable of calling class?

Hi all,

I’m having trouble issuing what I consider to be a simple one to many
relationship in rails. Here’s some code:

def SoccerPlayer < ActiveRecord::Base
has_many :goal_list, :class_name => ‘Goal’, :foreign_key =>
‘player_id’, :conditions => ‘player_name = #{last_name}’
end

Basically, I want goal_list to be a list of all goals scored by this
player. However, accessing goal_list gives me the following error.

“undefined method `last_name’ for Goal:Class”

So #{last_name} is referencing a Goal class, and not a SoccerPlayer
class. How do I get Rails to use the variable I want? Using
#{SoccerPlayer.last_name} doesn’t work either …

“undefined method ‘last_name’ for SoccerPlayer:Class” – but I clearly
access this variable further below on the page.

Ideas?

Thanks,
Ben

Hi –

On Mon, 28 Aug 2006, Ben wrote:

Hi all,

I’m having trouble issuing what I consider to be a simple one to many
relationship in rails. Here’s some code:

def SoccerPlayer < ActiveRecord::Base
has_many :goal_list, :class_name => ‘Goal’, :foreign_key =>
‘player_id’, :conditions => ‘player_name = #{last_name}’
end

This is a bit garbled. You need class, not def (def is for method
definitions), and the semantics are wrong: you don’t (I assume) want a
player to have many goal lists, but to have one list which has many
goals.

Also, you’re doing too much work. If you use a foreign key to
associate the goal with the player, then you don’t also need to check
the last name – and last names tend not to be unique anyway.

access this variable further below on the page.

Ideas?

I would start with this, and then tweak incrementally as necessary if
you want to change model or association names:

  1. In the database, make sure the goals table has a soccer_player_id
    field.

  2. In soccer_player.rb (the model file), do this:

    class SoccerPlayer < ActiveRecord::Base
    has_many :goals
    end

  3. In goal.rb, do this:

    class Goal < ActiveRecord::Base
    belongs_to :soccer_player
    end

  4. Now, when a goal is scored, in your controller you would do this
    (assuming that @player is the scorer and @goal is the goal):

    @player.goals << @goal

David


http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <-----
http://dablog.rubypal.com => D[avid ]A[. ]B[lack’s][ Web]log
Ruby for Rails => book, Ruby for Rails
http://www.rubycentral.org => Ruby Central, Inc.

Also, you’re doing too much work. If you use a foreign key to
associate the goal with the player, then you don’t also need to check
the last name – and last names tend not to be unique anyway.

Just for OP’s reference, the :conditions parameter is useful for doing
things like :conditions=>‘deleted = true’ or similar, not to model the
relationship itself, AR should take care of that.

Max