0

I got a bug in a bit of a complex part of a rails app and was curious when you need to use self to refer to the current object in a Rails model. I had (with the problematic lines beneath and commented out):

class Item < ActiveRecord::Base
....
def item_instore_enabled_changed list_is_instore_enabled # would be true or false
  if item_is_instore_enabled
    Rails.logger.info("this will be true with is_enabled_item: #{is_enabled_item}")
    self.is_enabled=true if self.is_enabled_item
    # is_enabled=true if is_enabled_menu_item - this didn't work
  end
  Rails.logger.info("BEFORE item save and is_enabled: #{is_enabled}")
  self.save! 
  # save  - didn't work
  Rails.logger.info("AFTER item save and is_enabled: #{is_enabled}")
end

Basically, I had to specify self.is_enabled rather than just is_enabled to assign a value and also could just call save! and had to call self.save!.

What are the rules for referring to self within an object or was there some other bug causing a problem with the above code?

jeffdill2
  • 3,968
  • 2
  • 30
  • 47
timpone
  • 19,235
  • 36
  • 121
  • 211
  • thx for comment - I used to always write with self. - but acknowledge that is longer. So when I `save` or `save!` nothing happens so not getting an error. Also, this is being called from another class so possibly self is the other class (which would be nasty)? – timpone Mar 22 '16 at 19:18
  • 1
    `is_enabled = true` should not work. If you were checking against it - i.e. `if is_enabled == true ...`, that should work correctly. But `is_enabled = true` should always need a `self` because Ruby has no idea if you're setting an attribute on the model or if you're defining a local variable. – jeffdill2 Mar 22 '16 at 19:21
  • 1
    Personally, I *always* use `self`. There are a lot of things that Ruby does implicitly that are really nice. But this is one area where I think being explicit is just much more clear and saves you a lot of potential headaches in the long run. – jeffdill2 Mar 22 '16 at 19:27
  • hmm... thx - that seems to be it. so it would seem like any assignment would require self? – timpone Mar 22 '16 at 19:36

0 Answers0