Hi, I have a model called Stock with a value called "strength." I
wrote a simple method in the Stock.rb model file to update the value
of "strength" for each record in the stocks table. I created a
controller called fix_controller.rb. I don't have access to the live
system, so the idea is that an admin will go to http://url/fix and a
script will run to check and potentially update the "strength" value
for every record in the stocks table.

fix_controller.rb
^^^^^^^^^^^^^^^
class FixController < ApplicationController

  def index
    stocks = Stock.find(:all)

    stocks.each do |s|
        if s.strength.nil? || s.strength == ''
          puts 'nothing to update'
        else
          s.update_units
        end
    end
  end
end

Stock.rb
^^^^^^^^^
def update_units
    if self.strength == '' || self.strength.nil?
   puts 'nil - cannot update'
elsif self.strength != '' && self.strength != nil
 self.strength = self.strength.gsub!(' ml', 'ml') if
self.strength.gsub!(' ml', 'ml') != nil
 self.strength = self.strength.gsub!(' mL', 'ml') if
self.strength.gsub!(' mL', 'ml') != nil
 self.strength = self.strength.gsub!(' g', 'g') if self.strength.gsub!
(' g', 'g') != nil
 self.strength = self.strength.gsub!(' oz', 'oz') if
self.strength.gsub!(' oz', 'oz') != nil
 self.strength = self.strength.gsub!(' mg', 'mg') if
self.strength.gsub!(' mg', 'mg') != nil
end

When I try to run this, I always get the error:

NoMethodError: private method `gsub' called for nil:NilClass

I'm sure this is a simple error and/or I'm not going about this the
correct way. I really only need to run this code once... Any idea why
I'm getting that error? I'm checking for nil...

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to