1

I'm having troubles with Globalize3 gem when updating cached attribute in after_commit callback.

#In My Model
after_commit :write_localized_caches
private
def write_localized_caches
  I18n.available_locales.each do |locale|
    Globalize.with_locale(locale) do
      self.write_attribute(:name, 'some localized string here')
    end
  end
end

It launches after_commit callbach and the value for the attribute is fine. But after all my model's name is still empty!

Maybe I'm misusing with_locale or does anyone faced the same problem?

UPDATE 1. I definitely want to use after_commit callback to perform complex queries on saved objects. Printing out self.name inside the callback returns just what i want: 'correct_string'. But id does not hit the Database. Ended up with writing a new translation creation. Seems like Globalize uses callback in its basement:

def write_localized_caches
I18n.available_locales.each do |locale|
  Globalize.with_locale(locale) do
    self.translations.create!(name: 'some localized string here', locale: locale)
  end
end
end

This works, but still does not feel right to me!

prikha
  • 1,853
  • 1
  • 16
  • 26

1 Answers1

0

After commit is called after the database has completed saving the record.

if you insert print statements such as

def write_localized_caches
  puts self.name # the name that you're seeing in the database

  # Globalize Block

  puts self.name # The name that was set above most likely
end

Also keep in mind that returning false or nil from a callback will abort the callback chain and reverse the database transaction. Though, after_commit is called after the transaction is complete, so it matters less here.

you probably want before_save. http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

EnabrenTane
  • 7,428
  • 2
  • 26
  • 44
  • Thanks for the links. I definitely want it to happen in after_commit callback because of complex queries. See the update above. – prikha Apr 19 '13 at 09:39