【问题标题】:Mongoid fields and subsequently added localizationMongoid 字段和随后添加的本地化
【发布时间】:2014-01-31 08:39:32
【问题描述】:

我以后添加本地化时有什么需要考虑的吗?

来自 类文章 字段:标题,类型:字符串 到 类文章 字段:标题,类型:字符串,本地化:true

我在我的Articles 模型上有内容,想随后添加本地化。

现在我发现有时内容会显示为哈希

{"en"=>"asdfasdf", "de"=>"123123123"}

有时作为普通文本。

如果我通过

显示文章
@article.title
# I get --> no implicit conversion from nil to integer


@article.title_translations
# I get --> no implicit conversion from nil to integer

如果文档未翻译,这种情况总是会发生。 (字符串)。

附加

另外,如果我尝试更改内容,我会遇到问题:

article.title # "en"
article.title_translations # "Test Title"
article.update_attribute(:name, c.name_translations)
# raises NoMethodError: undefined method `merge!' for "Test Title":String
article.name = c.title_translations
# raises NoMethodError: undefined method `merge!' for "Test Title":String

问题

  • 如何正确地将字符串字段更改为“String, :localize => true”?
  • 有要迁移的脚本或其他东西吗?

【问题讨论】:

  • 文档也许可以帮助你:mongoid.org/en/mongoid/docs/documents.html(本地化字段部分)
  • 不是真的,或者您的意思是手册中的特定部分。该手册仅描述了如何使用“新鲜”字段来做到这一点。但不是像字段类型更改这样的迁移。我的数据库已经充满了内容。

标签: ruby-on-rails-3 localization ruby-on-rails-3.2 mongoid mongoid3


【解决方案1】:

在前面的解决方案引发异常的情况下,我就是这样做的:

Article.all.each do |article|
  value = article.attributes['title'].try(:clone)
  unless value.is_a?(Hash)
    Article.collection.where({ _id: article._id }).update({
      "$set" => {
        "title" => I18n.available_locales.inject({}) do |m, l|
           m[l.to_s] = v
           m
         end
      }
    })
  end
end

【讨论】:

    【解决方案2】:

    内部通过哈希处理的翻译

    { "en" => "book", "de" => "Buch" }
    

    我已经解决了

    Article.each do |article|
      article.title_translations = {"en" => article.title_translations}
      article.save!
    end
    

    谢谢德登先生:

    https://github.com/mongoid/mongoid/issues/3488

    【讨论】:

      【解决方案3】:

      如果文档没有被翻译并且您尝试访问此字段,则会引发错误:

      no implicit conversion from nil to integer
      

      如果您尝试更改它,则会引发错误:

      raises NoMethodError: undefined method `merge!' for "Test Title":String
      

      这似乎是一个 mongoid 错误。现在,您可以在添加 'localize: true' 后为迁移执行此操作:

      I18n.locale = :en
      Article.all.each do |article|
        begin
          article.title
        rescue
          b = article.attributes['title']
          article.unset('title')
          article.title = b
          article.save
        end
      end
      

      这对我来说是个窍门。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多