如何使用 script/generate migration
命令来创建一个用于 has_and_belongs_to_many
关联的连接表?
本应用程序运行在 Rails 2.3.2 上,但我也安装了 Rails 3.0.3。
如何使用 script/generate migration
命令来创建一个用于 has_and_belongs_to_many
关联的连接表?
本应用程序运行在 Rails 2.3.2 上,但我也安装了 Rails 3.0.3。
地点:
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
create_table :students_teachers, :id => false do |t|
has_and_belongs_to_many
表必须匹配这个格式。我假设要连接的两个模型已经在数据库中: apples
和 oranges
。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)
:unique => true
,则应该(在rails3中)将:uniq => true
传递给has_and_belongs_to_many
。has_and_belongs_to_many
正常工作。script/generate migration
命令行完成它的方法... - ma11hew28您需要按照字母顺序将两个模型的名称命名为表格名称,并将这两个模型的ID放入表格中。然后在模型中创建彼此之间的关联,连接每个模型。
以下是一个例子:
# in migration
def self.up
create_table 'categories_products', :id => false do |t|
t.column :category_id, :integer
t.column :product_id, :integer
end
end
# models/product.rb
has_and_belongs_to_many :categories
# models/category.rb
has_and_belongs_to_many :products
但这种方法不够灵活,你应该考虑使用has_many :through。
顶级回答展示了一个综合指数,我不认为会用来查找苹果和橙子。
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.
# This enforces uniqueness and speeds up apple->oranges lookups.
add_index(:apples_oranges, [:apple_id, :orange_id], :unique => true)
# This speeds up orange->apple lookups
add_index(:apples_oranges, :orange_id)
我发现“The Doctor What”提供的答案非常有用,相关讨论也很有帮助。
在 Rails 4 中,你可以简单地使用
create_join_table :table1s, :table2s
就这样。
注意:你必须提供只包含字母数字的 table1 和 table2。
我喜欢做:
rails g migration CreateJoinedTable model1:references model2:references
。这样我就可以得到一个类似这样的迁移:
class CreateJoinedTable < ActiveRecord::Migration
def change
create_table :joined_tables do |t|
t.references :trip, index: true
t.references :category, index: true
end
add_foreign_key :joined_tables, :trips
add_foreign_key :joined_tables, :categories
end
end
我喜欢在这些列上建立索引,因为我经常会使用这些列进行查找。
迁移方法
create_join_table
创建一个HABTM(具有多个并属于多个)连接表。 一个典型的用途是:
create_join_table :products, :categories
默认情况下,连接表的名称来自于提供给 create_join_table 的前两个参数的字母顺序的并集。
rails generate migration CreateJoinTableTeacherStudent teacher student
而不是rails generate migration CreateJoinTableStudentTeacher student teacher
,这两者一样吗?S(tudent) 需要在 T(eacher) 之前吗? - zx1986