如何执行script/generate migration
来为has_and_belongs_to_many
关系创建连接表?
这个应用程序运行在Rails 2.3.2上,但我也安装了Rails 3.0.3。
发布于 2010-12-08 04:39:18
您应该按字母顺序将表命名为要连接的两个型号的名称,并将这两个型号的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:
发布于 2014-02-28 23:02:47
最上面的答案显示了一个综合索引,我认为它不会被用来从橙子中查找苹果。
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)
我确实找到了答案,这是基于“博士是什么”的有用的讨论,当然也是如此。
发布于 2014-10-16 09:45:18
在Rails4中,您可以简单地使用
create_join_table :table1,:table2
这就是全部。
注意:你必须使用字母数字的table1,table2。
https://stackoverflow.com/questions/4381154
复制相似问题