Ruby on rails 如何在rails中使用外键别名创建装置?
我有两种型号,Ruby on rails 如何在rails中使用外键别名创建装置?,ruby-on-rails,associations,rails-activerecord,fixtures,Ruby On Rails,Associations,Rails Activerecord,Fixtures,我有两种型号,App和User,其中App的创建者是用户 # 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 但这不起作用,因为关系是一个别名外键,而不是多态类型。在创建者行中省略
App
和User
,其中App
的创建者是用户
# 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
但这不起作用,因为关系是一个别名外键,而不是多态类型。在创建者行中省略(用户)
,也不起作用
我已经看到了几个关于外键和固定装置的帖子,但是没有一个真正响应这个。(许多人建议使用factory_girl或machinist或其他夹具替代品,但我在其他地方看到他们也有类似或其他问题)。从应用程序中删除(用户)。yml
。我用用户和应用程序复制了一个基本应用程序,但我无法复制您的问题。我怀疑这可能是由于您的数据库架构。检查您的架构,并确保您的应用程序表中有“creator\u 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,那么我怀疑这可能是您试图访问它们的方式。我编写的一个示例测试能够访问关联(请参见终端中的输出):
apps.yml
myapp:
name: MyApp
creator: admin
谢谢你,安德鲁·辛纳!我意识到我没有为测试环境调用fixture load。我现在调用了
rakedb:fixtures:load RAILS_ENV=test
,然后调用了RAILS c test
,删除(用户)
后缀后,它工作正常。
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "the truth" do
puts users(:admin).name
puts apps(:myapp).creator.name
end
end
class User < ActiveRecord::Base
has_many :apps, foreign_key: "creator_id"
end
class App < ActiveRecord::Base
belongs_to :creator, class_name: 'User'
end
admin:
name: Andrew
myapp:
name: MyApp
creator: admin