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.
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:
In the database, make sure the goals table has a soccer_player_id
field.
In soccer_player.rb (the model file), do this:
class SoccerPlayer < ActiveRecord::Base
has_many :goals
end
In goal.rb, do this:
class Goal < ActiveRecord::Base
belongs_to :soccer_player
end
Now, when a goal is scored, in your controller you would do this
(assuming that @player is the scorer and @goal is the goal):
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.