如何在Rails中创建具有外键别名的灯具? [英] How to create fixtures with foreign key alias in rails?

查看:105
本文介绍了如何在Rails中创建具有外键别名的灯具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,AppUser,其中App的创建者是User.

I have two models, App and User, where an App has a creator who is a 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

如何为此创建固定装置?

How do I create fixtures for this?

我尝试过:

# apps.yml
myapp:
    name: MyApp
    creator: admin (User)

# users.yml
admin:
    name: admin

但这是行不通的,因为该关系是别名外键,而不是多态类型.在创建者行中省略(User)也不起作用.

But this doesn't work, since the relation is an aliased foreign key, not a polymorphic type. Omitting the (User) in the creator line doesn't work either.

我已经看到了几个关于外键和固定装置的主题,但是它们都没有对此做出真正的回应. (许多建议使用factory_girl或机械师或其他替代固定装置的方法,但随后我在其他地方看到它们存在类似或其他问题).

I have seen several threads about Foreign Key and fixtures, but none of them really respond to this. (Many recommend using factory_girl or machinist or some other alternative to fixtures, but then I see elsewhere that they have similar or other problems).

推荐答案

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

Remove (User) from your apps.yml. I replicated a basic app with Users and App and I wasn't able to reproduce your problem. I suspect it may be due to your database schema. Check your schema and ensure you have a 'creator_id' column on your apps table. Here's my schema.

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,那么我怀疑这可能是您尝试访问它们的方式.我编写的示例测试能够访问该关联(请参见终端中的输出):

If not your schema.rb then I suspect it may be how you're trying to access them. An example test I wrote that was able to access the association (see the output in your terminal):

require 'test_helper'

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

我的两个模型是什么样的:

What my two models look like:

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:

users.yml:

admin:
  name: Andrew

apps.yml

myapp:
  name: MyApp
  creator: admin

这篇关于如何在Rails中创建具有外键别名的灯具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆