如何在rails中创建带有外键别名的灯具?

时间:2014-10-29 16:31:50

标签: ruby-on-rails associations rails-activerecord fixtures

我有两个模型,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)也不起作用。

我见过几个关于外键和灯具的线索,但没有一个真的回应过这个问题。 (许多人建议使用factory_girl或机械师或固定装置的其他替代品,但后来我在别处看到他们有类似或其他问题)。

1 个答案:

答案 0 :(得分:2)

apps.yml删除(用户)。我用用户和应用程序复制了一个基本应用程序,但我无法重现您的问题。我怀疑这可能是由于您的数据库架构。检查您的架构并确保您拥有&#39; creator_id&#39;应用程序表上的列。这是我的架构。

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