has_and_belongs_to_many连接表的Rails迁移?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (10)

我该怎么做script/generate migration若要为has_and_belongs_to_many关系?

应用程序运行在Rails 2.3.2上,但我也安装了Rails 3.0.3。

提问于
用户回答回答于

has_and_belongs_to_many表必须与此格式匹配。我假设这两种模式has_and_belongs_to_many已经在DB中:applesoranges:

create_table :apples_oranges, :id => false do |t|
  t.references :apple, :null => false
  t.references :orange, :null => false
end

# Adding the index can massively speed up join tables. Don't use the
# unique if you allow duplicates.
add_index(:apples_oranges, [:apple_id, :orange_id], :unique => true)

用户回答回答于

其中:

class Teacher < ActiveRecord::Base
  has_and_belongs_to_many :students
end

class Student < ActiveRecord::Base
  has_and_belongs_to_many :teachers
end

Rails 4:

rails generate migration CreateJoinTableStudentTeacher student teacher

Rails 3:

rails generate migration students_teachers student_id:integer teacher_id:integer

对于Rails<3

script/generate migration students_teachers student_id:integer teacher_id:integer

然后,对于Rails 3和更低版本,您需要编辑生成的迁移,这样就不会创建id字段:

create_table :students_teachers, :id => false do |t|

扫码关注云+社区