Jan
Jan

Reputation: 16074

Mongoid fields and subsequently added localization

Is there something to consider when I am adding localization later on?

from class Articles field :title, type: String to class Articles field :title, type: String, localize: true

I have content on my Articles model and wanna add localization subsequently.

Now I found out that sometimes content will be shown as a hash

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

and sometimes as normal text.

If I show an Article via

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


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

This happens always if a document was not translated. (String).

additional

Also if I try to alter the content I have problems:

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

Question

Upvotes: 4

Views: 923

Answers (3)

suruja
suruja

Reputation: 11

In the case of the previous solutions raise exceptions, this is what I do:

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

Upvotes: 1

Jan
Jan

Reputation: 16074

Translations internally handled via a hash

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

I've got it working with

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

Thank you Mr. Durden:

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

Upvotes: 1

rjurado01
rjurado01

Reputation: 5535

If a document was not translated and you try to access to this field, it raises an error:

no implicit conversion from nil to integer

If you try to change it it raises an error:

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

It seems a mongoid bug. For now, you can do this for migration after add '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

It made the trick for me.

Upvotes: 4

Related Questions