I don’t understand why I get a nil error below. But when I add self I don’t get the error and everything gets assigned corrected. Can you explain to me why if I don’t use self this does not work?
models/user.rb
def update_user_email!(new_email)
email = new_email # When I use self.name = new_email this works
end
controllers/users_controller
def create
@user = User.new(params[:user])
@user.update_user_email!(email)
@user.save
end
Thanks
When you are in a method inside a model, if you use just the attribute name it will treat it like a variable with the scope limited to this method. Using self.attribute will actually access the underlying field in the model and let you assign values.
As a basic rule, any time you are actually assigning values in a model, you should always use
On a side point, I am not sure if your code was for example only, but it doesn’t like look a method you would need.
In the controller you could just do