【问题标题】:Globalize.with_locale in after_commit callback does not change anythingafter_commit 回调中的 Globalize.with_locale 不会改变任何东西
【发布时间】:2013-04-18 09:23:53
【问题描述】:

我在更新 after_commit 回调中的缓存属性时遇到了 Globalize3 gem 的问题。

#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

这行得通,但我还是觉得不对劲!

【问题讨论】:

    标签: ruby-on-rails callback globalize3 rails-i18n


    【解决方案1】:

    在数据库完成保存记录后调用提交后。

    如果您插入打印语句,例如

    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 或 nil 将中止回调链并反转数据库事务。不过,after_commit 是在事务完成后调用的,所以这里没那么重要。

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

    【讨论】:

    • 感谢您的链接。由于复杂的查询,我绝对希望它发生在 after_commit 回调中。请参阅上面的更新。
    猜你喜欢
    • 2018-08-20
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2021-03-26
    • 2017-01-04
    相关资源
    最近更新 更多