加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:32:59 所属栏目:百科 来源:网络整理
导读:我在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 exec rails console 并
我在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
    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,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散列中分离出来.方法导致玩家模型首先被初始化

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读