Alexey Suslyakov Alexey Suslyakov - 2 months ago 8
Ruby Question

Why Ruby (or Rails) do things like this? (Unexpected model methods without "self" behavior)

I've got a validator in ActiveRecord model, in which I faced with some realy strange behavior.

Example:

if status_changed?
p status # output on line below
# <= "my_status_1"
p my_conditions_1 # output on line below
# <= false

if my_conditions_1
errors.add(:status, 'Error1')
status = status_was
end

p status # output on line below
# <= nil

# my_conditions_2 depends on "status variable"
if my_conditions_2
errors.add(:status, 'Error2')
status = 2
end
end


Second condition always failed, because
status
somehow was setted to nil. But when I changed
status
to
self.status
everything started working as expected.

Can someone explain it? Because I don't really get what's going on here. And I don't want to live in fear of missing
self
in models.

Answer

If you are updating the attribute then you must use self

self.status = 'something'

otherwise rails will assume status as a local variable so

puts self.status
#=> "something"

status = 'abc'

puts self.status 
#=> "something"

self.status = 'something else'
puts self.status 
#=> "something else"

But you can access the attribute with just status.

EDIT

why status was set to nil?

Maybe because of this line

status = status_was

before status_changed? maybe the self.status was nil

Comments