Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using self.attribute and attribute in a model?

Tags:

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 
like image 840
Some Guy Avatar asked Feb 26 '14 05:02

Some Guy


1 Answers

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.

like image 94
meagar Avatar answered Oct 22 '22 07:10

meagar