我正在使用rails 4.2.4,我想添加一个外键。
用户:
class User < ActiveRecord::Base
has_many :posts
validates :name, presence: true
end
发表:
class Post < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
end
迁移:
class AddForeignKeysToTables < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
end
create_table :posts do |t|
t.belongs_to :user
end
add_foreign_key :posts, :users
end
end
迁移报告:
== 20160224131802 AddForeignKeysToRfmAnalyticsTables: migrating ===============
-- create_table(:users)
-> 0.0150s
-> 0 rows
-- create_table(:posts)
-> 0.0150s
-> 0 rows
-- add_foreign_key(:posts, :users)
-> 0.0000s
== 20160224131802 AddForeignKeysToTables: migrated (0.0300s) ======
在MySQL数据库中添加foreign_key无法正常运行。并没有创建一个外键。您是否有任何想法如何在此示例中创建外键?
但是我想在迁移中保留belongs_to,因为这就像旧的迁移一样,add_foreign_key必须是新的迁移。
也许相关的宝石:
jruby_version = '1.7.22'
gem 'rails', '4.2.4'
gem 'activerecord-jdbcmysql-adapter'
来自schema.rb的脚本:
create_table "posts", force: :cascade do |t|
t.integer "user_id", limit: 11
end
create_table "users", force: :cascade do |t|
t.string "name", limit: 255
end
如果我使用像'foreigner'或'foreign_keys'这样的宝石,那么就会创建外键,但这些宝石似乎不兼容。