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

时间:2011-06-12 23:30:03

标签: ruby-on-rails foreign-keys

当有多对多的关系时,你必须显式创建中间连接表吗?如何向迁移添加外键?我有一个用户模型和一个书模型。我安装了foreigner。到目前为止,这是我的代码。有人可以告诉我如何从这里开始吗?

USER

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

1 个答案:

答案 0 :(得分:2)

是的,你需要一个联接表。使用has_and_belongs_to_many时的约定是将连接表命名为model1_model2。因此,在这种情况下,您的迁移需要看起来像这样:

create_table :books_users, :id => false do |t|
  t.integer :user_id, :null => false
  t.integer :book_id, :null => false
end

请注意:id =&gt; false部分,这是为了确保连接表不会自动获取自己的id。