【问题标题】:How can I load Globalize translation fixtures to test models?如何加载 Globalize 翻译装置来测试模型?
【发布时间】:2015-11-15 06:36:11
【问题描述】:

我在 Rails 4.1.12 中使用 gobalize gem 4.0.3。

我有一个Post 模型,并且我运行了globalize 提供的Post.create_translation_table! 迁移来设置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', '2015-08-21 10:23:27', 626768522)

如果我做相反的事情会发生类似的错误(即posts.yml中的post_translation: my_first_translation

我如何找回魔法?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord fixtures globalize


    【解决方案1】:

    解决方案

    1. fixtures/post_translations.yml 移动到fixtures/post/translations.yml
    2. 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
    

    说明

    1. 翻译模型是Post::Translation。命名空间意味着Post::Translation 固定装置的位置必须遵循与app/models 中的模型相同的嵌套约定。

    2. Post::Translation(以及任何globalize 翻译模型)上的关联名称为globalized_modelActiveRecord::FixtureSetuses the association name to recognise the fixture key as an association.

    【讨论】:

    • 戴夫,非常感谢您在这个问题上的帮助!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多