如何在Rails中使用外键别名创建测试数据?

3
我有两个模型,AppUser,其中一个 App 有一个创建者,他是一个 User
# app.rb
class App < ActiveRecord::Base
  belongs_to :creator, class_name: 'User'  
end

# user.rb
class User < ActiveRecord::Base
  has_many :apps, foreign_key: "creator_id"
end

如何为此创建夹具?
我尝试过:
# apps.yml
myapp:
    name: MyApp
    creator: admin (User)

# users.yml
admin:
    name: admin

但是这并不起作用,因为关系是一个别名外键,而不是多态类型。在创建者行中省略(User)也不起作用。
我看过几个关于Foreign Key和fixtures的线程,但它们都没有真正回应这个问题。(许多人建议使用factory_girl或machinist或其他替代fixtures的工具,但我在其他地方看到它们有类似或其他问题)。
1个回答

2
从你的apps.yml中删除(User)。我复制了一个包含用户和应用程序的基本应用程序,但我无法重现你的问题。我怀疑这可能是由于你的数据库模式引起的。检查你的模式并确保你在应用程序表上有一个“creator_id”列。下面是我的模式。
ActiveRecord::Schema.define(version: 20141029172139) do
  create_table "apps", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "creator_id"
    t.string   "name"
  end

  add_index "apps", ["creator_id"], name: "index_apps_on_creator_id"

  create_table "users", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "name"
  end
end

如果不是你的schema.rb文件,我怀疑可能是你尝试访问它们的方式。我写了一个示例测试,能够访问关联(请参阅终端中的输出):

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "the truth" do
    puts users(:admin).name
    puts apps(:myapp).creator.name
  end
end

我的两个模型长什么样:

user.rb

class User < ActiveRecord::Base
  has_many :apps, foreign_key: "creator_id"
end

app.rb

class App < ActiveRecord::Base
  belongs_to :creator, class_name: 'User'  
end

我的YML文件:

users.yml:

admin:
  name: Andrew

apps.yml

myapp:
  name: MyApp
  creator: admin

谢谢,@andrew-sinner!我意识到我没有为测试环境调用装置加载。现在我调用了 rake db:fixtures:load RAILS_ENV=test,然后调用了 rails c test,在删除 (User) 后它就正常工作了。 - Anand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接