Hi. I've tried to redefine the method belongs_to in ActiveRecord::Base, so every time a model is defined as belonging to :attachment, it should have some additional methods. I tried to do an alias of belongs_to, but this was not successful. The error message in Webrick was
Booting WEBrick...
./script/../config/../lib/ActiveRecordExtensions.rb:67: undefined method `belongs_to' for module `ActiveRecord' (NameError)
The code with problem is:
alias :attachment_belongs_to :belongs_to def belongs_to(association_id, options={}) self.attachment_belongs_to(association_id,options) if association_id == :attachment
code = <<EOS alias :tmp_attach= :attachment= def attachment=(content) if content.class.name == 'Attachment' #old functionality self.tmp_attach=(content) else if content.class.name.match(/^Hash/) && content["content"] && content["content"].original_filename != "" if self.attachment self.attachment.update_attributes(content) else attach = Attachment.new(content) attach.save self.tmp_attach=(attach) end end end end
alias :tmp_destroy :destroy
def destroy
attach = self.attachment
self.tmp_destroy
attach.destroy if attach
end
EOS
module_eval(code)
end
end