In Ruby on Rails, what's the difference between using self.attribute and attribute in a model?
In this example, assume my_attr is an attribute of the user that gets stored in the database.
class User < ActiveRecord::Base def do_something! self.my_attr = 123 end def do_another_thing! my_attr = 456 end end
The difference in your examples is that the first one works, the second doesn't.
Your second version isn't doing anything (at least nothing meaningful). Writing my_attr = 123
is not equivalent to self.my_attr = 123
. Instead it's creating a local variable called my_attr
and setting it to 123
, and then immediately reaching the end of the method and throwing my_attr
away. The whole method is essentially a no-op, and it doesn't affect the model's my_attr
value in any way.
class User < ActiveRecord::Base def do_another_thing! my_attr = 456 puts self.my_attr # nil (or whatever value it was before) end end
Conversely, if you want to access a method defined on an object, you can (and should) omit self
:
class User def name=(value) @name = value end def name @name end def age=(value) @age = value end def age @age end def do_something self.name = "bob" # self is required puts name # bob (self.name) age = 47 # @age is unaffected age # 47 (local variable), but self.age is nil end end
Note that, this isn't a Rails question, it's a Ruby question. There is no Rails-specific code here, this behaviour is part of how Ruby's syntax works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With