我有两个模型 restaurant
和 user
,我想对它们执行 has_and_belongs_to_many 关系。
我已经进入模型文件并添加了 has_and_belongs_to_many :restaurants
和 has_and_belongs_to_many :users
我认为此时我应该能够做类似 Rails 3 的事情:
rails generate migration ....
但我尝试过的一切似乎都失败了。我确信这非常简单,我是 Rails 新手,所以我仍在学习。
最佳答案
您需要添加一个单独的联接表,其中仅包含 restaurant_id
和 user_id
(无主键),并按字母顺序排列。
首先运行迁移,然后编辑生成的迁移文件。
Rails 3
rails g migration create_restaurants_users_table
Rails 4:
rails g migration create_restaurants_users
Rails 5
rails g migration CreateJoinTableRestaurantUser restaurants users
来自docs :
<小时/>There is also a generator which will produce join tables if JoinTable is part of the name:
您的迁移文件(请注意 :id => false
;它会阻止创建主键):
Rails 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
Rails 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
将自动创建必要的索引。 defchange
将自动检测前向或回滚迁移,无需向上/向下。
Rails 5
create_join_table :restaurants, :users do |t|
t.index [:restaurant_id, :user_id]
end
注意:还有一个自定义表名称选项,可以作为参数传递给名为 table_name
的 create_join_table。来自 docs
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:
关于ruby-on-rails - Rails has_and_belongs_to_many 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561330/