几年前(2013年),我编写了一个迁移来全球化我的模型的一个字段,使用globalize 0.3.0,Rails 3.2.21,Ruby2.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我添加了相应的翻译属性:
translates :name, required: true现在我想添加第二个全球化属性title,所以我将这一行添加到MyModel中:
translates :title即使在编写第二个迁移脚本之前,我也会删除数据库并执行所有迁移。
bundle exec rake db:drop db:create db:migrate我注意到我在2013年编写的迁移脚本正在失败。这怎麽可能?这是我现在所知道的。
我的2013年迁移脚本中的方法create_translation_table!正在将模型中找到的所有可翻译字段(即:name和:title )添加到翻译表中。IMHO,这有点奇怪,因为这段代码实际上正在执行在创建迁移后可能添加到模型中的数据库更改。
全球化的gem试图猜测:title的类型,但它似乎失败了,因为我在执行2013年迁移脚本时得到了这个错误:
Bad field type for field :title (nil), should be :string or :text
我正在寻找一种方法来实现这些选择:
:title创建列,并创建一个2015年迁移脚本,以添加该列无te转换表(我认为此选项更好):title是字符串(我已经尝试过translates :title, :string,但似乎不起作用)。发布于 2015-12-15 08:20:17
我以前也遇到过类似的问题,找到的解决方案之一就是总是在迁移中指定转换的属性:
def up
MyModel.translated_attribute_names = [:name]
MyModel.create_translation_table! name: :string
end还建议完全避免全球化生成器,并手动创建翻译表:
create_table :my_model_translations do |t|
t.references :my_model
t.string :locale
t.string :name
endhttps://stackoverflow.com/questions/34196494
复制相似问题