I'm working in Rails and have the following class:
class Player < ActiveRecord::Base
attr_accessor :name, :rating, :team_name
def initialize(name, rating, team_name)
@name = name
@rating = rating
@team_name = team_name
end
end
When I run
bundle exec rails console
and try:
a = Player.new("me", 5.0, "UCLA")
I get back:
=> #<Player not initialized>
I have no idea why the Player object wouldn't be initialized here. Any suggestions on what to do / explanation for what might be causing this?
Thanks, Mariogs
have no idea why the Player object wouldn't be initialized here
It's not initilised quite simply because you have not initialised it!
You have overriden the ActiveRecord::Base initialize method but you are not calling through to it it so the Player class is not initialised properly
Just call super
class Player < ActiveRecord::Base
attr_accessor :name, :rating, :team_name
def initialize(name, rating, team_name)
super
@name = name
@rating = rating
@team_name = team_name
end
end
You probably didn't mean to override the initialize method at all, it's strongly discouraged http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html, you probably meant to make use of the after_initialize callback so you can split the name, rating and team_rating out from the params hash that is passed in to whatever method causes the player model to be intialised in the first place
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With