ruby-on-rails - 未在 Ruby 中初始化的对象

标签 ruby-on-rails ruby

我在 Rails 工作并有以下类(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

当我运行时

bundle exec rails console

然后尝试:

a = Player.new("me", 5.0, "UCLA")

我回来了:

 => #<Player not initialized>

我不知道为什么 Player 对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?

谢谢, 马里奥格

最佳答案

have no idea why the Player object wouldn't be initialized here

它没有初始化很简单,因为你还没有初始化它!

您已经覆盖了 ActiveRecord::Base 初始化方法,但您没有调用它,所以 Player 类没有正确初始化

只要调用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

您可能根本不想重写初始化方法,强烈建议不要这样做 http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html ,您可能打算使用 after_initialize 回调,这样您就可以将名称、评级和 team_rating 从传入的任何方法的参数哈希中分离出来,从而导致玩家模型首先被初始化

关于ruby-on-rails - 未在 Ruby 中初始化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22726551/

相关文章:

javascript - 包括 ActionController::Live 会中断现有的 AJAX 调用

ruby-on-rails - ActiveModel 基于关联验证属性

mysql - 如果使用原始 ActiveRecord::Base.connection(),如何获取最后插入的主键值?

ruby-on-rails - 如何设置标签的最小和最大数量?

ruby - 检查 ruby​​ 散列是否包含大于 x 的值

ruby-on-rails - rails : Undefined method `truncate' in model

ruby-on-rails - 将类添加到 collection_select

ruby-on-rails - rails : new asset path for PDF's not being recognised

python - 解析 XML - 适合这项工作的脚本语言/包?

ruby - 当你有类时查找方法的 source_location