开发者

How do you add foreign key in many to many relationship?

When having many to many relationship do you have to explicitly create the intermediate join table? How do I add foreign-keys to migration? I have a user model and a book model. I have foreigner installed. Here is my code so far. Can somebody show me how to proceed from here please?

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

BOOK MODEL

class Book < ActiveRecord::Base
   has_and_belongs_to_many :users
end

MIGRATION FOR BOOKS

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

MIGRATION FOR USER

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


Yes, you'll need a join table. The convention when using has_and_belongs_to_many is to name the join table like model1_model2. So in this case your migration would need to look something like this:

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

Notice the :id => false part, that's to make sure that the join table doesn't automatically get its own id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜