Reputation: 27583
I am suddenly completely lost with scope of variables in Rails with Mongoid. (Probably due to a lack of coffee).
All I want, is a way to set certain fields from within the application, but the only way I can find to do this, is by calling write_attribute
.
class Example
include Mongoid::Document
field :foo
def bar
@foo = "meh"
end
def hmpf
foo = "blah"
end
def baz
write_attribute(:foo, "meh")
end
end
e.bar #=> "meh"
e.foo #=> nil
e.hmpf #=> "blah"
e.foo #=> nil
e.baz #=> [nil, "meh"]
e.foo #=> "meh"
Am I using the scope wrong? Why will running foo = "bar"
not set the field from within, it works from outside: e.foo = "blah"
works trough the magic methods.
Upvotes: 0
Views: 436
Reputation: 9649
Try adding self
to your attribute references when working in your model's instance methods:
def hmpf
self.foo = "blah"
end
Should do the trick.
Upvotes: 1