所以我刚刚创建了一个迁移文件,迁移了它,并编写了我的"播放器"类。我试图运行此代码:
def get_most_recent_ladder
@top_80 = Team.all
# loop through all teams, add each player and their rating to the hash, sort by rating, limit to 200
all_players = []
@top_80.each do |team|
url = "http://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=#{team.team_id}"
doc = Nokogiri::HTML(open(url))
player_names = doc.css('.table.table-bordered.table-striped.table-condensed')[1].css('tr td a').map(&:content)
player_ratings = doc.css('.table.table-bordered.table-striped.table-condensed')[1].css('tr td:nth-child(4)').map(&:content)
for i in (0..player_names.length-1)
player = Player.create(player_names[i], player_ratings[i].to_f, team.name)
all_players << player
end
end
all_players = all_players.sort{|player1, player2| player1.rating <=> player2.rating}.reverse.first(200)
#insert creation of ladder object with order
@ladder = all_players
render 'ladder'
end
不幸的是,当我运行代码时,Rails给了我一个&#34;错误数量的参数(3代表0..2)。所以有一些事情:
1)这是我的Player类:
class Player < ActiveRecord::Base
attr_accessible :name, :rating, :team
end
因此,它应该需要3个参数来创建Player类的新实例。
2)我不知道为什么会显示&#34; 0..2&#34;而不是正常的整数。
3)此外,我现在正在&#34;未初始化的常量PagesController :: Player。
这是我使用的HAML布局:
#ladder
%tr
%th Player
%th Rating
%th Team
%tr
-@ladder.each do |player|
%td player.name
%td player.rating
%td player.team
出于某种原因,它会打印出我的标题,然后打印出&#34; player.name&#34;,&#34; player.rating&#34;,&#34; player.team&#34;一遍又一遍,而不是每个玩家的实际名称,评级和团队......
思想?
非常困惑所以任何帮助都会很棒!
谢谢, Mariogs
答案 0 :(得分:2)
问题在于您的create
电话。您需要将参数作为哈希提供:
player = Player.create(:name => player_names[i], :rating => player_ratings[i].to_f, :team => team.name)
这是因为Rails无法知道你提供的3个参数应该匹配你的3个字段(你永远不应该假设Rails会保持字段顺序)。通过提供具有特定键的哈希值(例如:name
,:rating
等),Rails可以将您的值与您的字段正确匹配。
如果要在.haml
文件中显示这些值,请在项目前使用=
:
%td= player.name
%td= player.rating
%td= player.team