How to create fixtures with foreign key alias in rails?

六月ゝ 毕业季﹏ 提交于 2019-12-04 19:26:20

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

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

My YML files:

users.yml:

admin:
  name: Andrew

apps.yml

myapp:
  name: MyApp
  creator: admin
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!