How to create fixtures with foreign key alias in rails?

妖精的绣舞 提交于 2019-12-21 22:02:28

问题


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?

I tried:

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

# users.yml
admin:
    name: admin

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.

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).


回答1:


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


来源:https://stackoverflow.com/questions/26635832/how-to-create-fixtures-with-foreign-key-alias-in-rails

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