2013-04-18 45 views
1

我在after_commit回調中更新緩存屬性時遇到了Globalize3 gem的問題。after_commit回調中的globalize.with_locale不會改變任何東西

#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 

它啓動after_commit callbach並且屬性值很好。但畢竟我的模特的名字還是空的!

也許我在濫用with_locale還是有人遇到同樣的問題?

更新1. 我絕對想使用after_commit回調來對保存的對象執行復雜的查詢。 在回調中打印出self.name只返回我想要的:'correct_string'。但是id沒有打到數據庫。 完成寫作新的翻譯創作。好像Globalize的使用回調在其地下室:

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 

這工作,但仍然不覺得我的權利!

回答

0

在數據庫完成保存記錄後調用commit之後。如果插入打印語句,如

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 

而且記住,返回false或零從一個回調將中止回調鏈和反向數據庫事務

。雖然after_commit在事務完成後被調用,所以它在這裏不重要。

你可能想要before_save。 http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

+0

感謝您的聯繫。由於複雜的查詢,我一定希望它在after_commit回調中發生。看到上面的更新。 – prikha

相關問題