Nil error?

Hi everyone,

I’m sure I’m doing something stupid with this, so if somebody could talk
some sense into me that would be great :slight_smile:

I’m trying to just increment a variable and I think I’m missing some
basic concept (this is RoR 2.0.2 btw)

So have a “players” table with several variables, including one called
“odds”. I’m using the basic scaffold generator for the CRUD stuff, but
in my model I have:

attr_reader :odds

def initialize(odds)
@odds = odds
end

def winGame
@odds += 1
end

(note: attr_reader makes the odds in the index list disappear from
view.)

in the controller I have:

def winner
player = Player.find(params[:id])
player.winGame

respond_to do |format|
  format.html { redirect_to(players_url) }
  format.xml  { head :ok }
end

end

and in the view I have:

<%= link_to 'Win Game', :action => "winner", :id => player %>

This results in:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

I can view the correct odds number by using ‘puts odds.to_s’ but it
won’t let me set it at any point. Am I missing something?

Thanks in advance!

Gary H. wrote:

Hi everyone,

I’m sure I’m doing something stupid with this, so if somebody could talk
some sense into me that would be great :slight_smile:

I’m trying to just increment a variable and I think I’m missing some
basic concept (this is RoR 2.0.2 btw)

So have a “players” table with several variables, including one called
“odds”. I’m using the basic scaffold generator for the CRUD stuff, but
in my model I have:

attr_reader :odds

def initialize(odds)
@odds = odds
end

This results in:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

I can view the correct odds number by using ‘puts odds.to_s’ but it
won’t let me set it at any point. Am I missing something?

Thanks in advance!

This is just a guess, but I would try replacing attr_reader with
attr_accessor. It may be that since you’re not telling ruby to make a
method for setting odds, that it is unable to set it via the @odds
variable.

I’m no expert, but I play one on tv.

cheers,
jp

The attributes that Rails creates by reading the content_columns from
a db table are not instance variables as in a traditional Ruby class.
They are actually all stored in an internal hash called attributes,
and Rails does some method_missing magic to create accessors for you.
By creating the accessor for odds as you have, you’ve effectively
aliased the db column.

Instead, you can initialize your player object like this:

Player.new(:odds=>…)

and your win_game method:

def win_game
self.odds += 1 (or update_attributes(:odds, self.odds+1) if you want
to persist it immediately)
end

HTH,
AndyV

On Feb 16, 1:14 pm, “Gary H.” [email protected]