ruby - 如何在事件记录中正确添加外键?

标签 ruby ruby-on-rails-4 activerecord

我试图在多个表中创建一些引用完整性,但在添加外键的位置上遇到了障碍。充其量该语句会被忽略,最坏的情况是它会引发错误。

class CreateCantons < ActiveRecord::Migration
def change
create_table :cantons do |t|
  t.integer :canton_id
  t.string :canton_name

  t.timestamps null: false
end
end
end

class CreateResources < ActiveRecord::Migration
def change
create_table :resources do |t|
  t.integer :resource_id
  t.string :resource_name
  t.integer :type_id
  t.integer :canton_id
  t.string :url
  t.string :address
  t.string :city
  t.string :state
  t.string :zip
  add_foreign_key :cantons, :canton_id #ignored
  add_foreign_key :types, :type_id #ignored

  t.timestamps null: false
end
end
end

class CreateResourceContacts < ActiveRecord::Migration
def change
create_table :resource_contacts do |t|
  t.integer :contact_id
  t.integer :resource_id
  add_foreign_key :resources, :resource_id
  add_foreign_key :contacts, :contact_id

  t.timestamps null: false
end
end
end

在前面加一个t会报错

t.add_foreign_key :contacts, :contact_id #error

如何正确使用这个命令?

最佳答案

您需要将外键移到创建表之外

class CreateResources < ActiveRecord::Migration
  def change
    create_table :resources do |t|
      t.integer :resource_id
      t.string :resource_name
      t.integer :type_id
      t.integer :canton_id
      t.string :url
      t.string :address
      t.string :city
      t.string :state
      t.string :zip

      t.timestamps null: false
    end

    add_foreign_key :resources, :cantons
    add_foreign_key :resources, :types 

  end
end

参见http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key

而且您还需要告诉它您要将其添加到哪些表中。

关于ruby - 如何在事件记录中正确添加外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212536/

相关文章:

ruby-on-rails - 没有 Rails 的事件记录 : How to pass an Arbitrary hash to Active Record

ruby-on-rails - RSpec 请求警告 - Rails 5.1 升级 - Assets 管道中不存在 Assets

ruby-on-rails - 我的抓取 "stack"应该如何处理 404 错误?

ruby-on-rails - 获取特定参数的值 - Rails

sql - ActiveRecord 查找 - 跳过记录或获取每 N 个记录

ruby - "it"关键字在 RSpec 中有什么作用?

mysql - Carrierwave 多次上传失败并显示 mount_uploaders

javascript - 如何将嵌套的Rails ActiveRecord查询结果传递给gon?

ruby-on-rails - 使用 Rails 3 构建和处理多个参数查询

mysql - Rails 中的复杂 MySQL 查询