Ruby on rails RubyonRails-如何在应用程序控制器中使用外部类

Ruby on rails RubyonRails-如何在应用程序控制器中使用外部类,ruby-on-rails,ruby,Ruby On Rails,Ruby,我目前正在尝试自学RubyonRails。我设置了一个新的应用程序,并使其启动和运行,然后我创建了一个新类-Player,并将其保存在app>models目录中(根据我的阅读,它是从这里自动加载的): player.rb class Player @@players = {} def initialise(name, rating=50) @name = name @rating = rating @@players[name] = rating end

我目前正在尝试自学RubyonRails。我设置了一个新的应用程序,并使其启动和运行,然后我创建了一个新类-
Player
,并将其保存在
app>models
目录中(根据我的阅读,它是从这里自动加载的):

player.rb

class Player
  @@players = {}
  def initialise(name, rating=50)
    @name = name
    @rating = rating
    @@players[name] = rating
  end

  def getName()
    return @name
  end
end
class IndexController < ApplicationController
    def index
      player1 = Player.new("Martin", 90)
    end
end
<h1>Test</h1>


<%=  player1.getName() %>
索引\u控制器\u rb

class Player
  @@players = {}
  def initialise(name, rating=50)
    @name = name
    @rating = rating
    @@players[name] = rating
  end

  def getName()
    return @name
  end
end
class IndexController < ApplicationController
    def index
      player1 = Player.new("Martin", 90)
    end
end
<h1>Test</h1>


<%=  player1.getName() %>
class IndexController
index.html.erb

class Player
  @@players = {}
  def initialise(name, rating=50)
    @name = name
    @rating = rating
    @@players[name] = rating
  end

  def getName()
    return @name
  end
end
class IndexController < ApplicationController
    def index
      player1 = Player.new("Martin", 90)
    end
end
<h1>Test</h1>


<%=  player1.getName() %>
测试
我得到的错误是


参数数目错误(2代表0)
您做得很对,并且假设正确。错误告诉您找到了该类,但您尝试调用的方法不支持2个参数。默认的
initialize
方法接受零参数,当您发送两个参数时,它会在您身上爆炸

这是因为您只是拼错了
initialize
方法名,所以没有使用包含2个参数的版本覆盖它

这:

应该是:

def initialize(name, rating=50)
#           ^ a "z" here
现在,当调用
Player.new(“Martin”,90)
时,您的
初始化(名称、评级)
版本将被正确调用


其次,你似乎想把球员传给你的观点。为此,播放器需要是一个实例变量(以
@
符号开头)。否则,它是一个局部变量,永远不会离开
index
controller方法的范围。实例变量将传递给视图

控制器:

class IndexController < ApplicationController
  def index
    @player1 = Player.new("Martin", 90)
  end
end
class IndexController
视图:



ah*********,谢谢。我讨厌提出问题,因为这是一个微不足道的错误。我现在得到了一个不同的错误
未定义的局部变量或方法
player1',对于#`你知道这将要拯救我的理智吗?通过添加
@
使
player1
成为一个实例变量,所以
@player1=Player.new(“Martin”,90)
就是你想要的你说他做得对,他将外部类存储在模型中。存储类或库/任务的位置是否正确?