Rails has_and_belongs_to_many 迁移
我有两个模型 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 新手,所以我仍在学习。
I have two models restaurant
and user
that I want to perform a has_and_belongs_to_many relationship.
I have already gone into the model files and added the has_and_belongs_to_many :restaurants
and has_and_belongs_to_many :users
I assume at this point I should be able to do something like with Rails 3:
rails generate migration ....
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要添加一个单独的联接表,其中仅包含
restaurant_id
和user_id
(无主键),并按字母顺序排列。首先运行迁移,然后编辑生成的迁移文件。
Rails 3
Rails 4:
Rails 5
来自 文档:
您的迁移文件(请注意
:id => false
;它会阻止创建主键):Rails 3
Rails 4
t.belongs_to
将自动创建必要的索引。defchange
将自动检测前向或回滚迁移,无需向上/向下。Rails 5
注意:还有一个自定义表名称选项,可以作为参数传递给名为
table_name
的 create_join_table。来自文档You need to add a separate join table with only a
restaurant_id
anduser_id
(no primary key), in alphabetical order.First run your migrations, then edit the generated migration file.
Rails 3
Rails 4:
Rails 5
From the docs:
Your migration file (note the
:id => false
; it's what prevents the creation of a primary key):Rails 3
Rails 4
t.belongs_to
will automatically create the necessary indices.def change
will auto detect a forward or rollback migration, no need for up/down.Rails 5
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这里的答案已经相当过时了。从 Rails 4.0.2 开始,您的迁移使用
create_join_table
。要创建迁移,请运行:
这将生成以下内容:
如果您想对这些列建立索引,请取消注释相应的行,然后就可以开始了!
The answers here are quite dated. As of Rails 4.0.2, your migrations make use of
create_join_table
.To create the migration, run:
This will generate the following:
If you want to index these columns, uncomment the respective lines and you're good to go!
创建联接表时,请特别注意迁移名称/类中两个表需要按字母顺序列出的要求。如果您的型号名称相似,例如“abc”和“abb”,这很容易让您感到困扰。如果你要竞选,
你的关系将无法按预期运作。您必须使用
它来代替。
When creating the join table, pay careful attention to the requirement that the two tables need to be listed in alphabetical order in the migration name/class. This can easily bite you if your model names are similar, e.g. "abc" and "abb". If you were to run
Your relations will not work as expected. You must use
instead.
对于 HABTM 关系,您需要创建一个联接表。只有连接表,并且该表不应有 id 列。尝试这个迁移。
您必须检查 这种关系rails指导教程
For HABTM relationships, you need to create a join table. There is only join table and that table should not have an id column. Try this migration.
You must check this relationship rails guide tutorials