kevin kariuki kevin kariuki - 5 months ago 21
Ruby Question

undefined method `admn_no' for nil:NilClass

I have two models Scorecard and Result

The relationship between the two is;

class Scorecard < ActiveRecord::Base
belongs_to :results

class Result < ActiveRecord::Base
has_many :scorecards
after_save :export_params


The model Scorecard is supposed to do a bunch of calculations and output them in a view. This is happening. It is then supposed to take a copy of the current results from the calculation and save them to Result. This is not happening.
Model Scorecard has an after_save filter that triggers the save to Result. It is supposed to check if the current admission number exists in theResult model.
If if does, it is updated, if not, it is created. To create;


assign_attributes


to update


update_attributes


the implementation is as follows

def export_params
case admn_no
when Result.where(:admno => self.admn_no).exists?
@results.update_attributes(:admno => @scorecard.admn_no)
else
@results.assign_attributes(:admno => @scorecard.admn_no)
end end


here is the error



Result Exists (0.1ms) SELECT 1 AS one FROM "results" WHERE "results"."admno" = ? LIMIT 1 [["admno", 3457]]
(0.2ms) rollback transaction
Completed 500 Internal Server Error in 123ms (ActiveRecord: 5.3ms)

NoMethodError (undefined method `admn_no' for nil:NilClass):
app/models/scorecard.rb:1127:in `export_params'
app/controllers/scorecards_controller.rb:23:in `create'




Answer Source

I finally solved it :). here is how I did it-

when Result.where(:admno => self.admn_no).first_or_create do |result|
result.admno=self.admn_no
 end

thankyou, your suggestions certainly pointed this the direction it needed