For a User model with columns :first_name and :last_name, what is the best way to write the full_name method. Both seem to work.
class User < ActiveRecord::Base
def full_name
first_name + last_name
end
end
Or
class User < ActiveRecord::Base
def full_name
self.first_name + self.last_name
end
end
I've looked at the SO posts below but am not sure
Why isn't self always needed in ruby / rails / activerecord?
This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state "parent = value" Ruby assumes you want to assign the value to the local variable parent.
Somewhere up the stack there's a setter method "def parent=" and to call that you must use "self.parent = " to tell ruby that you actually want to call a setter and not just set a local variable.
When it comes to getters Ruby looks to see if there's a local variable first and if can't find it then it tries to find a method with the same name which is why your getter method works without "self".
In other words it's not the fault of Rails, but it's how Ruby works inherently."
Why isn't self always needed in ruby / rails / activerecord?
Why use “self” to access ActiveRecord/Rails model properties?
"Often the use of self is to force Ruby to recognize that as a method call and not mis-interpret it as a variable. Without prior knowledge of a method called day=, then day = "x" looks to Ruby like a variable assignment. self.day = "x" is always a method call.
The reason this is trouble is because the name and name= methods are added dynamically after the User class file has been parsed. The first thing Rails does when using a model is make methods for the associated database fields, but this happens after your user.rb file is parsed."
Why use "self" to access ActiveRecord/Rails model properties?