Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migration error using Globalize

Some years ago (2013) I wrote a migration to globalize one of the fields of my model using Globalize 0.3.0, Rails 3.2.21, Ruby 2.1.6:

class CreateMyModelTranslationTable < ActiveRecord::Migration
  def up
    change_table :my_model do |t|
      t.remove  :name
    end
    MyModel.create_translation_table! name: :string
  end

  def down
    change_table :my_model do |t|
      t.string :name
    end
    MyModel.drop_translation_table! 
  end
end

And I added its corresponding translation attribute:

translates :name, required: true

Now I want to add a second globalized attribute named title, so I added this line to MyModel:

translates :title

Even before writing the second migration script, I drop my database and execute all migrations.

bundle exec rake db:drop db:create db:migrate

I notice the migration script I wrote in 2013 is failing. How is this possible? This is what I know up to now.

The method create_translation_table! in my 2013 migration script is adding to the translation table all the translatable fields found in the model, that is, both :name and :title. IMHO, this is a bit strange because this code is in fact performing database changes that may have been added to the model after the creation of the migration.

Globalize gem tries to guess the type of :title and it seems to fail, because I am getting this error while executing the 2013 migration script:

Bad field type for field :title (nil), should be :string or :text

I am looking for a way to achieve any of these options:

  • Prevent Globalize from creating a column for :title when running 2013 migration script, and create a 2015 migration script to add this column no te translation table (I think this option is better)
  • Find out how to specify in the model that :title is a string (I have already tried translates :title, :string and does not seem to work).
like image 802
Bustikiller Avatar asked Dec 10 '15 07:12

Bustikiller


1 Answers

I had a similar problem before and one of the solutions a found was to always specify the translated attributes in the migration:

def up
  MyModel.translated_attribute_names = [:name]
  MyModel.create_translation_table! name: :string
end

It was also suggested to avoid the globalize generators altogether and to create the translations tables manually:

create_table :my_model_translations do |t|
  t.references :my_model
  t.string :locale
  t.string :name
end
like image 182
Plamena Gancheva Avatar answered Sep 18 '22 13:09

Plamena Gancheva