加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何将Globalize翻译装置加载到测试模型?

发布时间:2020-12-17 04:02:28 所属栏目:百科 来源:网络整理
导读:我在Rails 4.1.12中使用gobalize gem 4.0.3. 我有一个Post模型,我运行Post.create_translation_table! globalize提供的迁移,用于设置post_translations表. 现在我想自动加载夹具文件的翻译.夹具支持label references for associations所以我有这个: # spec
我在Rails 4.1.12中使用gobalize gem 4.0.3.

我有一个Post模型,我运行Post.create_translation_table! globalize提供的迁移,用于设置post_translations表.

现在我想自动加载夹具文件的翻译.夹具支持label references for associations所以我有这个:

# spec/fixtures/posts.yml

my_first_post:
  author: dave

# spec/fixtures/post_translations.yml

my_first_post_translation:
  locale: en    
  title: My first post
  content: What a time to be alive!
  post: my_first_post

# spec/models/post_spec

require 'rails_helper'

RSpec.describe Post,type: :model do
  fixtures('post/translations',:posts,:authors)

  subject(:post) { posts(:my_first_post) }

  it "has an author" do
    expect(post.author).to eq(authors(:dave))
  end

  it "has a title" do
    binding.pry
    expect(post.title).to be_present
  end
end

但运行RSpec会引发以下错误:

Failure/Error: Unable to find matching line from backtrace
 ActiveRecord::StatementInvalid:
   SQLite3::SQLException: table post_translations has no column named post: INSERT INTO "post_translations" ("locale","title","content","post","created_at","updated_at","id") VALUES ('en','My first post','This is some compelling english content','my_first_post','2015-08-21 10:23:27',626768522)

如果我执行逆操作会发生类似的错误(即post.tral中的post_translation:my_first_translation)

我如何获得魔法?

解决方法

>将fixtures / post_translations.yml移动到fixtures / post / translations.yml
> my_first_translation中关联的关键是globalized_model

所以你最终得到这个:

<!-- language: yml -->
# spec/fixtures/posts.yml

my_first_post:
  author: dave

# spec/fixtures/post/translations.yml

my_first_post_translation:
  locale: en
  title: My first post
  content: What a time to be alive!
  globalized_model: my_first_post

说明

>翻译模型是Post :: Translation.命名空间意味着Post :: Translation夹具的位置必须遵循与app / models中的模型相同的嵌套约定.
> Post :: Translation(以及任何全球化翻译模型)上的关联名称为globalized_model. ActiveRecord :: FixtureSet uses the association name to recognise the fixture key as an association.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读