Search code examples
ruby-on-railsrubyobjectnullmember

Why am I getting a nil value from a Ruby object's member, when it is not nil?


I want to get the value of a field (ScenarioID) in a Ruby ActivityChart object (chart). Displaying the whole chart shows the value I want: 160.

The problem was chart.Scenario yielded the nil value. This could be reproduced in two ways: 1) by referencing chart.Scenario in the program, or by printing chart.Scenario in the debugger.

The chart object:

#<ActivityChart
  id: 1,
  ChartName: "Pipe 304 Chart",
  OverrideStartTime: nil,
  OverrideStopTime: nil,
  UseStartTime: false,
  UseStopTime: false,
  UseRecentSeconds: false,
  created_at: "2020-02-21 17:39:13",
  updated_at: "2020-03-02 16:17:22",
  RecentSeconds: nil,
  UseConcentrationCal: false,
  PercentComplete: 100.0,
  ShowOnDashboard: false,
  ScenarioID: 160>

ScenarioID is obviously not nil, yet that is what I'm getting in the program, and here in the debugger:

(byebug) p chart.id
1
(byebug) p chart.PercentComplete
100.0
(byebug) p chart.ScenarioID
nil

I get correct values for the other members, only ScenarioID is returning nil. Why is this happening? (I've only been programming in Ruby for a week, so it may be an obvious error.) Thanks!

EDIT: Here is the class ScenarioID appears in:

class ActivityChart < ApplicationRecord
    attr_accessor :ScenarioID
    validates :ChartName, presence: true, allow_blank: false
    validates :ScenarioID, presence: true
    validate :oneAndOnlyOne

    def oneAndOnlyOne
        if self.UseRecentSeconds && self.RecentSeconds == nil
            errors.add(:RecentSeconds, 'can\'t be blank')
        end
    end
end

Solution

  • I've solved the problem: chart.ScenarioID is the way I'd do it in C++ and it doesn't work here; it returns nil.

    In Ruby, chart[:ScenarioID] works, and correctly returns 160.