Reputation: 7855
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.
Upvotes: 0
Views: 267
Reputation: 31
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
Upvotes: 0
Reputation: 10898
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.
Upvotes: 0
Reputation: 115511
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.
Upvotes: 0
Reputation: 1208
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.
Upvotes: 1