-4

If I have a class in Rails:

class Ticket < ActiveRecord::Base
  def update_status
    return if status == 'sold'
    return unless reserved_until.nil? || reserved_until.past?
    self.status = 'open'
  end
end

where status and reserved_until are fields in the database for the Ticket model, why do I only have to use self when I am assigning a value?

ThomYorkkke
  • 2,061
  • 3
  • 18
  • 26

3 Answers3

2

Because if you do status = 'open' you are creating a new local variable called status. That's not about Rails. That is about how Ruby interpreter evaluate your code.

dx7
  • 804
  • 5
  • 11
1

The accepted answer here explains it pretty well. -> When to use self in Model?

To read further in depth this is an excellent blog that puts it clearly. http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

Community
  • 1
  • 1
Shifa Khan
  • 769
  • 6
  • 12
0

Whenever you want to invoke a setter method on self, you have to write self.status = "open". If you just write status = "open", the ruby parser recognizes that as a variable assignment and thinks of status as a local variable from now on. For the parser to realize, that you want to invoke a setter method, and not assign a local variable, you have to write obj.status = "open", so if the object is self, self.status = "open"

mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51