如何在多对多关系中添加外键?

问题描述

| 当存在多对多关系时,您必须显式创建中间联接表吗?如何在迁移中添加外键?我有一个用户模型和一个书模型。我安装了外国人。到目前为止,这是我的代码。有人可以告诉我如何从这里继续吗? 用户
class User < ActiveRecord::Base
  has_and_belongs_to_many :books
  # Include default devise modules. Others available are:
  # :token_authenticatable,:lockable,:timeoutable and :activatable
  devise :database_authenticatable,:registerable,:recoverable,:rememberable,:trackable,:validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email,:password,:password_confirmation
end
预订模型
class Book < ActiveRecord::Base
   has_and_belongs_to_many :users
end
图书迁移
class CreateBooks < ActiveRecord::Migration

  def self.up
    create_table :books do |t|
      t.string :title
      t.string :author
      t.timestamps
    end
  end

  def self.down
    drop_table :books
  end
end
供用户迁移
class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable
      # t.lockable :lock_strategy => :failed_attempts,:unlock_strategy => :both
      t.timestamps
    end
    add_index :users,:email,:unique => true
    add_index :users,:reset_password_token,:unique => true
    # add_index :users,:unlock_token,:unique => true
  end

  def self.down
    drop_table :users
  end
end
    

解决方法

        是的,您将需要一个联接表。使用“ 4”时的约定是将连接表命名为“ 5”。因此,在这种情况下,您的迁移需要看起来像这样:
create_table :books_users,:id => false do |t|
  t.integer :user_id,:null => false
  t.integer :book_id,:null => false
end
注意:id => false部分,这是为了确保联接表不会自动获得其自己的ID。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...