Alexey Suslyakov Alexey Suslyakov - 1 year ago 50
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.


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

p status # output on line below
# <= nil

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

Second condition always failed, because
somehow was setted to nil. But when I changed
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
in models.

Answer Source

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.


why status was set to nil?

Maybe because of this line

status = status_was

before status_changed? maybe the self.status was nil

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download