Search code examples
ruby-on-railsrubyruby-on-rails-5.2

undefined method `-' for nil:NilClass for active record callback of existing field


I have a form with a checkbox of different styles. The form works fine, but I am getting an empty string saved in the array of style options. I would like to remove it. So I created a before_save callback..

Parameters: {"utf8"=>"✓","car_form"=>{"styles"=>["","Black"]}}

VIEW

<%= f.input :styles, as: :check_boxes, collection: FormCollection::Styles.all %>

MODEL

class Car < ApplicationRecord
  before_save :remove_empty_from_styles

  def remove_empty_from_styles
     styles = (styles - ['']) if styles_changed?
  end
end

However, I get:

undefined method `-' for nil:NilClass

However, if I comment out the call back everything works fine, the values get saved, like normal.

NOTES: styles is not nil.


Solution

  • You need to access styles on self:

    def remove_empty_from_styles
      self.styles = styles - [''] if styles_changed?
    end
    

    styles = styles - [''] assigns the result of styles - [''] to a local variable called styles.

    self.styles = styles - [''] invokes a styles= method on self passing styles - [''] as an argument.