0

Can anyone help with this?Thanks in advance for your reply.

In app/controllers/heats_controller.rb, the code is as below:

class HeatsController < ApplicationController
  def add_car
    Pusher[params[:sendTo]].trigger('addCar', car_params)
    head :ok
  end

  def index
    @heats = Heat.all
    render json: @heats
  end

  def new

    race = Race.all.sample

    render json: { start_time: Time.now.to_s,
                   race_id: race.id,
                   text: race.passage }
  end

  def show
    @heat = Heat.find(params[:id])
  end

  def start_game
    Pusher[params[:sendTo]].trigger('initiateCountDown', start_heat_params)
    head :ok
  end

  def update_board
    Pusher[params[:channel]].trigger('updateBoard', car_params)
    head :ok
  end

  private
  def heat_params
    params.require(:heat).permit(:race_id)
  end

  def car_params
    params.permit(:racer_id,
                  :racer_name,
                  :return_to,
                  :progress,
                  :racer_img,
                  :wpm,
                  :channel,
                  :sendTo)
  end

  def start_heat_params
    params.permit(:channel, :race_id, :text, :timer)
  end
end

In app/models/heat.rb, the code is as below:

class Heat < ActiveRecord::Base
  belongs_to :race
  has_many :racer_stats
end

Any help will be appreciated ,thank you


Error:

Processing by HeatsController#new as */*
Completed 500 Internal Server Error in 6ms

NoMethodError (undefined method `id' for nil:NilClass):
  app/controllers/heats_controller.rb:18:in `new'
Richard Peck
  • 76,116
  • 9
  • 93
  • 147

3 Answers3

0

It seems that Race.all.sample does not work.

Maybe you have no records in races table at all.

Also, try this to retrieve random record (for Rails 4):

def new
   offset = rand(Race.count)
   Race.offset(offset).first
   ...
end
0

The error is here:

def new
  ... race_id: race.id ...
end

race doesn't have any data, so calling .id on it won't work. You're also calling Race.all.sample (very bad), which means you've probably got no records in your Race model.


If you want to pick a random record, you should use this answer to pull one:

def new
   race = Race.order("RAND()").first #-> MYSQL
   render json: { start_time: Time.now.to_s, race_id: race.id, text: race.passage } unless race.nil?
end
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

You could do:

render json: { start_time: Time.now.to_s,
                   race_id: race.try(:id),
                   text: race.try(:passage) }

This would fix the whiny nil error if your .sample returns nil. But I agree that all.sample is bad practice.

rlarcombe
  • 2,958
  • 1
  • 17
  • 22