Is there a way to generate a Rails model with a many to many relationship predefined? I know how to add it to the Active Record after the fact but it would be nice to have it defined in the DB migration and the Active Record model right off the bat.
有没有办法生成一个预定义的多对多关系的Rails模型?事实上我知道如何将它添加到Active Record中,但是在DB迁移和Active Record模型中定义它是很好的。
3 个解决方案
#1
17
Remember that you do not want an id for the join table, so make sure to add :id => false |t|
请记住,您不希望连接表的ID,因此请确保添加:id => false | t |
create_table assemblies_parts, :id => false do |t|
t.integer :assembly_id
t.integer :part_id
end
If you use rails
如果你使用rails
rails generate model Assemblies_parts assembly:references part:references
you will have two indexes, but what you want is
你将有两个索引,但你想要的是
# Add table index
add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true
UPDATE
UPDATE
- For Rails 5 use
create_join_table
instead. - 对于Rails 5,请使用create_join_table。
#2
3
You can use this reference from the Rails Guides.Here is the link. Also you will need to manually create the join table for those models using a migration.
您可以使用Rails指南中的此引用。这是链接。此外,您还需要使用迁移为这些模型手动创建连接表。
e.g
例如
create_table :assemblies_parts, :force => true do |t|
t.integer :assembly_id
t.integer :part_id
end
#3
1
Please look at this question first: Creating a many-to-many relationship in Rails 3.
请先看看这个问题:在Rails 3中创建多对多关系。
In addition, I would recommend next book "Ruby on Rails 3 Tutorial: Learn Rails by Example" for a better understanding of ActiveRecord
relations.
另外,为了更好地理解ActiveRecord关系,我建议下一本书“Ruby on Rails 3教程:通过示例学习Rails”。
#1
17
Remember that you do not want an id for the join table, so make sure to add :id => false |t|
请记住,您不希望连接表的ID,因此请确保添加:id => false | t |
create_table assemblies_parts, :id => false do |t|
t.integer :assembly_id
t.integer :part_id
end
If you use rails
如果你使用rails
rails generate model Assemblies_parts assembly:references part:references
you will have two indexes, but what you want is
你将有两个索引,但你想要的是
# Add table index
add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true
UPDATE
UPDATE
- For Rails 5 use
create_join_table
instead. - 对于Rails 5,请使用create_join_table。
#2
3
You can use this reference from the Rails Guides.Here is the link. Also you will need to manually create the join table for those models using a migration.
您可以使用Rails指南中的此引用。这是链接。此外,您还需要使用迁移为这些模型手动创建连接表。
e.g
例如
create_table :assemblies_parts, :force => true do |t|
t.integer :assembly_id
t.integer :part_id
end
#3
1
Please look at this question first: Creating a many-to-many relationship in Rails 3.
请先看看这个问题:在Rails 3中创建多对多关系。
In addition, I would recommend next book "Ruby on Rails 3 Tutorial: Learn Rails by Example" for a better understanding of ActiveRecord
relations.
另外,为了更好地理解ActiveRecord关系,我建议下一本书“Ruby on Rails 3教程:通过示例学习Rails”。