简体   繁体   中英

Wrong Number of Arguments Error in RoR App? Unsure why

So I've just created a migration file, migrated it, and written my "Player" class. I'm trying to run this code:

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

Unfortunately, When I run the code, Rails gives me a "Wrong number of arguments (3 for 0..2). So a few things:

1) Here's my Player class:

class Player < ActiveRecord::Base
  attr_accessible :name, :rating, :team
end

So it should need 3 arguments to create a new instance of the Player class.

2) I don't know why it displays "0..2" instead of a normal integer.

3) Also, I'm now getting "Uninitialized Constant PagesController::Player.

Here's the HAML layout I'm using:

#ladder
  %tr
    %th Player
    %th Rating
    %th Team
  %tr
    -@ladder.each do |player|
      %td player.name
      %td player.rating
      %td player.team

For some reason, it prints out my headings, but then literally prints out "player.name", "player.rating", "player.team" over and over again instead of each player's actual name, rating, and team...

Thoughts?

Pretty confused so any help would be awesome!

Thanks, Mariogs

The problem is your create call. You need to supply the arguments as a hash:

player = Player.create(:name => player_names[i], :rating => player_ratings[i].to_f, :team => team.name)

This is because there is no way for Rails to know that the 3 parameters you supplied are supposed to match up to your 3 fields (and you should never assume Rails will keep the fields in that order anyway). By supplying a hash with specific keys (eg :name , :rating , etc.) Rails can properly match up your values with your fields.

When you want to display these values in your .haml files, use = before the items:

%td= player.name
%td= player.rating
%td= player.team

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM