Reputation: 65113
Here is my AR Model:
class MyObject < ActiveRecord::Base
include ContentSyntax # where parse_out_variables is defined
serialize :variables
def save
self.variables = ContentSyntax.parse_out_variables(self.body)
super
end
end
now, in my app, I do my_object.update_attributes(params)
which worked fine before I tried to extend save.
The Error I get is this:
TypeError (class or module required):
app/models/my_object.rb:64:in `save'
But I want this code to execute every time the object is saved. (Or if just one attribute (the 'body') is changed, that would be better)
What is the right way to do this?
EDIT:
using a before_save callback:
before_save {
self.variables = ContentSyntax.parse_out_variables(self.body)
}
I now have the error:
NoMethodError (undefined method `body' for #<Class:0x10a0866b8>):
but... it exists!
Upvotes: 0
Views: 319
Reputation: 434635
Using a before_save
callback is the right way to do this. However, when you use a block with an ActiveRecord callback, the object in question is passed to the block as an argument so you'd want something more like this:
before_save { |o| o.variables = o.parse_out_variables(o.body) }
or maybe this:
before_save :add_variables
private
def add_variables
self.variables = parse_out_variables(self.body)
end
Upvotes: 3