【问题标题】:How to create fixtures with foreign key alias in rails?如何在rails中创建具有外键别名的夹具?
【发布时间】:2014-10-29 16:31:50
【问题描述】:

我有两个模型,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 或机械师或其他固定装置的替代品,但后来我在其他地方看到他们有类似或其他问题)。

【问题讨论】:

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


    【解决方案1】:

    从您的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
    

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

    用户.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)后缀后就正常了。
    猜你喜欢
    • 1970-01-01
    • 2014-06-23
    • 2021-11-23
    • 1970-01-01
    • 2018-03-28
    • 2011-12-13
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    相关资源
    最近更新 更多