我在Rails工作并拥有以下课程: class Player ActiveRecord::Base attr_accessor :name, :rating, :team_name def initialize(name, rating, team_name) @name = name @rating = rating @team_name = team_name endend 我跑的时候 bundle ex
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
我跑的时候
bundle exec rails console
并尝试:
a = Player.new("me", 5.0, "UCLA")
我回来了:
=> #<Player not initialized>
我不知道为什么Player对象不会在这里初始化.关于该怎么做/解释可能导致这种情况的任何建议?
谢谢,
Mariogs
have no idea why the Player object wouldn’t be initialized here
它不是很简单,因为你没有初始化它!
您已经覆盖了ActiveRecord :: Base初始化方法,但是您没有调用它,因此Player类未正确初始化
只需打电话给超级
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
您可能根本不打算覆盖初始化方法,强烈建议不要使用http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html,您可能打算使用after_initialize回调,这样您就可以将名称,等级和team_rating从传递给任何内容的params散列中分离出来.方法导致玩家模型首先被初始化