在Ruby on Rails中生成具有多对多的模型

有没有办法生成一个预定义的多对多关系的Rails模型? 事实上我知道如何将它添加到Active Record中,但是在DB迁移和Active Record模型中定义它是很好的。

请记住,您不希望连接表的ID,因此请确保添加:id => false | t |

create_table assemblies_parts, :id => false do |t| t.integer :assembly_id t.integer :part_id end 

如果你使用rails

 rails generate model Assemblies_parts assembly:references part:references 

你将有两个索引,但你想要的是

 # Add table index add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true 

UPDATE

  • 对于Rails 5,请使用create_join_table

您可以使用Rails指南中的此引用。 这是链接 。 此外,您还需要使用迁移为这些模型手动创建连接表。

例如

  create_table :assemblies_parts, :force => true do |t| t.integer :assembly_id t.integer :part_id end 

请先看看这个问题: 在Rails 3中创建多对多关系 。

另外,为了更好地理解ActiveRecord关系,我建议下一本书“Ruby on Rails 3教程:通过示例学习Rails” 。