2

This is very basic but not working. I want to add a callback (after_save) to upcase a field input.

In my model I have:

after_save :upcase_tax_label

def upcase_tax_label
   self.tax1_label.upcase!
   self.tax2_label.upcase!
end

So when I edit it should upcase the value and render in CAPS. but not. What's wrong? Thanks for your help

Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
Olivier
  • 661
  • 2
  • 10
  • 13
  • 1
    Agreed. Olivier, you're more likely to get people to continue to answer your questions of you accept their answers. :) – Shaun Jan 26 '11 at 22:00
  • didn't know I had to accept answers. Will do now. Thanks. But any idea to solve my issue? – Olivier Jan 27 '11 at 20:53

2 Answers2

3

after_save is going to run the upcase methods after the model has already been saved to the database. In other words, it's just upcasing the object attributes in memory after the save has already completed. That's not what you want.

You want to instead use before_save so that the attributes are upcased before the object is written to the database:

before_save :upcase_tax_label

private
def upcase_tax_label
   tax1_label.upcase!
   tax2_label.upcase!
end

Bottom line is that you have to explicitly save a model for the changes to be made in the database. Until then, you're just playing with an object in memory.

danneu
  • 9,244
  • 3
  • 35
  • 63
1
before_save 

will work. however, it's generally considered better style to write a custom setter in this situation. it would look something like this:

def tax1_label=(val)
  write_attribute(:tax1_label, val.upcase)
end

def tax2_label=(val)
  write_attribute(:tax2_label, val.upcase)
end
sirmxanot
  • 43
  • 8