繁体   English   中英

为什么从Fixtures加载的Rails数据损坏了?

[英]Why Rails data loaded from Fixtures are broken?

我有两个关于“语言环境”和“翻译”的Fixture文件。 语言环境可以很好地加载,但是翻译会被破坏:

治具

translation_05064:
  id: 5064
  key: control.base_search_users.panel.title
  value: Поиск пользователей
  interpolations: 
  locale: ru
  locale_id: 16
  is_proc: false

成为记录:

#<Translation id: 5064, 
key: "control.base_search_users.panel.title", 
value: "Поиск пользователей", 
interpolations: nil, 
locale: nil, 
locale_id: 1019186233, 
is_proc: false>

由于某种原因,对于文件中的每个夹具, locale而不是'ru'都变为nil,而locale_ib而不是16变为1019186233

我以这种方式加载灯具:

require 'active_record/fixtures'
ActiveRecord::Fixtures.reset_cache  
fixtures_folder = File.join(Rails.root, 'test', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
ActiveRecord::Fixtures.create_fixtures(fixtures_folder, fixtures)

翻译模型

class Translation < ActiveRecord::Base
  validates :key, :uniqueness => {:scope => :locale_id}
  validates :key, :locale, :locale_id, :value, :presence => true
  belongs_to :locale
  attr_accessible :key, :value, :locale_id, :locale
end

迁移

  class CreateTranslations < ActiveRecord::Migration
    def change
      create_table :translations do |t|
        t.string  :key
        t.text    :value
        t.text    :interpolations
        t.string  :locale
        t.integer :locale_id
        t.boolean :is_proc, :default => false
      end
      add_index :translations, [:key, :locale]
    end
  end

我在插入数据库的test.log中看到包含损坏的数据。 当我将夹具文件加载到YAML.load_file 'test/fixtures/translations.yml' rails concl中时,我得到了正确的哈希数据。

为什么会这样? 如何解决? Rails-2.3.8PostgreSQL 8.4


更新:尝试命名灯具。 在locales.yml中:

locale_00016:
  id: 16
  code: ru
  name: Русский

并在translations.yml中将所有区域设置键值设置为locale_00016

translation_05064:
  id: 5064
  key: control.base_search_users.panel.title
  value: Поиск пользователей
  locale: locale_00016
  is_proc: false

是的,那行得通!

翻译ID引用了现有的正确的Locale记录,但是语言环境仍然为零,要修复它,我运行Locale.find_by_code('ru').translations.update_all(:locale => 'ru')

如果设置了locale_id ,看起来还可以; 需要时(第一次请求时),Rails将填充locale 1019186233是rais在创建固定装置时生成的ID。

大多数时候,您不需要在固定装置中指定ID,Rails会为您生成ID,因此,如下所示的固定装置就可以了(您不应在Translation固定装置中同时定义localelocale_id ):

locales.yml:

ru:
  what_ever_attr: value
  ...

translations.yml:

ru_title_translation:
  key: control.base_search_users.panel.title
  value: Поиск пользователей
  interpolations: 
  locale: ru
  is_proc: false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM