Rails has_and_belongs_to_many迁移 [英] Rails has_and_belongs_to_many migration
问题描述
我有两个要执行has_and_belongs_to_many关系的模型restaurant
和user
.
I have two models restaurant
and user
that I want to perform a has_and_belongs_to_many relationship.
我已经进入模型文件并添加了has_and_belongs_to_many :restaurants
和has_and_belongs_to_many :users
I have already gone into the model files and added the has_and_belongs_to_many :restaurants
and has_and_belongs_to_many :users
我认为在这一点上我应该能够对Rails 3进行类似的操作.
I assume at this point I should be able to do something like with Rails 3:
rails generate migration ....
但是我尝试过的一切似乎都失败了.我确信这是非常简单的事情,我是Rails的新手,所以我还在学习.
but everything I have tried seems to fail. I'm sure this is something really simple I'm new to rails so I'm still learning.
推荐答案
您需要以字母顺序添加仅包含restaurant_id
和user_id
(无主键)的单独的联接表. >.
You need to add a separate join table with only a restaurant_id
and user_id
(no primary key), in alphabetical order.
首先运行您的迁移,然后编辑生成的迁移文件.
First run your migrations, then edit the generated migration file.
路轨3
rails g migration create_restaurants_users_table
路轨4 :
rails g migration create_restaurants_users
路轨5
rails g migration CreateJoinTableRestaurantUser restaurants users
从文档:
如果JoinTable,还有一个生成器将生成联接表 是名称的一部分:
There is also a generator which will produce join tables if JoinTable is part of the name:
您的迁移文件(请注意:id => false
;这是阻止创建主键的原因):
Your migration file (note the :id => false
; it's what prevents the creation of a primary key):
路轨3
class CreateRestaurantsUsers < ActiveRecord::Migration
def self.up
create_table :restaurants_users, :id => false do |t|
t.references :restaurant
t.references :user
end
add_index :restaurants_users, [:restaurant_id, :user_id]
add_index :restaurants_users, :user_id
end
def self.down
drop_table :restaurants_users
end
end
路轨4
class CreateRestaurantsUsers < ActiveRecord::Migration
def change
create_table :restaurants_users, id: false do |t|
t.belongs_to :restaurant
t.belongs_to :user
end
end
end
t.belongs_to
将自动创建必要的索引. def change
将自动检测向前或向后迁移,而无需进行上/下迁移.
t.belongs_to
will automatically create the necessary indices. def change
will auto detect a forward or rollback migration, no need for up/down.
路轨5
create_join_table :restaurants, :users do |t|
t.index [:restaurant_id, :user_id]
end
注意:还有一个自定义表名称的选项,可以作为参数传递给名为table_name
的create_join_table.从文档
Note: There is also an option for a custom table name that can be passed as a parameter to create_join_table called table_name
. From the docs
默认情况下,联接表的名称来自于 提供给create_join_table的前两个参数,按字母顺序 命令.要自定义表的名称,请提供:table_name 选项:
By default, the name of the join table comes from the union of the first two arguments provided to create_join_table, in alphabetical order. To customize the name of the table, provide a :table_name option:
这篇关于Rails has_and_belongs_to_many迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!