我正在使用Rails 4.2.3。如何创建将列添加到与表类型相同的表的迁移?此外,如何添加外键(如果列为NULL,则可以)?我试过这个
class AddLinkedMyObjectToMyObjects < ActiveRecord::Migration
def change
add_reference :my_objects, :linked_my_object, type: :my_object, index: true, foreign_key: true
end
end
但是我在运行迁移时遇到了这个错误
== 20160616201701 AddLinkedMyObjectToMyObjects: migrating =============================
-- add_reference(:my_objects, :linked_my_object, {:type=>:my_object, :index=>true, :foreign_key=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedObject: ERROR: type "my_object" does not exist
LINE 1: ALTER TABLE "MyObjects" ADD "linked_my_object_id" my_object
^
: ALTER TABLE "MyObjects" ADD "linked_my_object_id" my_object
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract_adapter.rb:472:in `block in log'
答案 0 :(得分:1)
我认为您需要“手动”执行此操作:
add_column :my_objects, :linked_my_object_id, :integer
add_index :my_objects, :linked_my_object_id
add_foreign_key :my_objects, :my_objects, column: :linked_my_object_id
然后在MyObject
课程中说:
belongs_to :linked_my_object, class_name: MyObject
has_many :my_objects, foreign_key: :linked_my_object_id
答案 1 :(得分:1)
我做了类似的事情。 我会在引用用户的articles表中添加引用。这样做的是在articles表中创建一个名为 user_id 的索引。
1:生成迁移的命令是:
rails generate migration add_user_id_to_articles user:references
2:结果迁移将是:
class AddUserIdToArticles < ActiveRecord::Migration
def change
add_reference :articles, :user, index: true, foreign_key: true
end
end
3:在终端
中运行rake db:migrate
4:scheme.rb文件中的迁移结果如下: 你可以在哪里看到添加了t.integer“user_id”
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "visits_count"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
5:要进行关联,我会添加到article.rb模型
belongs_to :user
然后,在user.rb模型中
has_many :articles