0

I'm just learning rails and have noticed that when I create an object that inherits from ActiveRecord::Base (i.e. from a model I migrated), the instance variables in the object do not have a @ symbol in front of them.

Is this a rails thing, or did I misunderstand something while learning ruby?

Thanks in advance for your help.

Nathan
  • 7,627
  • 11
  • 46
  • 80

4 Answers4

1

Rails doesn't use individual instance variables to store field data. Instead it makes certain methods available to you which set the correct variables. It helps Rails better populate models when using finds and allows other methods that improve how dynamic Rails is.

Darren Coxall
  • 1,208
  • 11
  • 11
0

The columns of your model are not stricto sensu instance variables.

You have access to their getter/setter but they are by nature different: they are meant to be persisted.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
0

Rails defines getter/setter for all model attributes.

Getter/setter can ben declared with attr_accessor function.

class Foo
  attr_accessor :bar

  def do_something
     self.bar=2
     @bar=2 # does the same as above
  end
end
  • Interesting. I didn't know you can set @bar by passing a value directly to the setter method as in your example: bar=2 – Nathan Mar 09 '12 at 09:33
  • @Nathan actually bar=2 doesn't work: http://stackoverflow.com/questions/5963076/understand-self-for-attr-accessor-class-method – bixente.bvd Feb 19 '13 at 14:43
0

When accessing the "instance variables" of your object, you're actually interacting with the getter/setter methods defined by rails which in turn interact with the real instance variables.

This is actually very useful as it allows you to override them when required to modify the behaviour of the variables within your classes.

Jon
  • 10,678
  • 2
  • 36
  • 48