我有两个模型,App
和User
,其中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)
也不起作用。
我看到了一些关于外键和fixture的帖子,但没有一个真正对此做出回应。(许多人建议使用factory_girl或机械师或其他夹具的替代品,但我在其他地方看到他们也有类似或其他问题)。
从apps.yml
中删除(用户)。我用用户和应用程序复制了一个基本的应用程序,但我无法重现你的问题。我怀疑这可能是由于您的数据库架构。检查您的架构,并确保您的应用程序表上有一个"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