has_and_belongs_to_many:多对多

0
视频
0
完成
0%
进度
0
分钟
0
完成
0%
进度

一个文章可以有多个标签,一个标签也可以属于多个文章 ... 这种关系,我们可以使用 has_and_belongs_to_many 去描述一下 ..

先创建一个标签模型 ... 名字是 Tag .. 添加一个 title 栏,类型是 string

rails generate model Tag title:string

找到创建的这个 Tag 模型 ... 用一下 has_and_belongs_to_many :posts ... 标签可以有多个文章 ... 再打开文章模型 ... 同样用一下 has_and_belongs_to_many :tags ... 文章可以有多个标签 ..

这种类型的关系我们需要一个中间表 ... 先去创建一个 migration .... 名字是 CreatePostsTags .. 这个中间表的名字用的是 posts 与 tags 表合在一块儿的名字 ... posts 在 tags 的前面,因为字母 p 在字母 t 的前面 ..

rails generate migration CreatePostsTags

找到这个 migration .. 编辑一下 ... 这个中间表不需要 id 栏,所以可以使用一个 id: false ...

再添加一个 t.belongs_to :post, index: true ... 接着再添加一个 t.belongs_to :tag, index.true ..

这样会在这个表里添加两个栏,post_id 还有 tag_id,它们都是这个表的外键 ..

运行一下 migration .... rails db:migrate

完成以后可以查看一下数据库里的数组表 ... 这里会多了一个 posts_tags 表 .. 再检查一下它的结构 ... 表里有两栏内容 ... post_id,对应的是 posts 表里的 id 栏, 还有 tag_id ,对应的 tags 表里的 id 栏 ...

has_and_belongs_to_many:多对多《 Rails:关联 》

统计

14696
分钟
0
你学会了
0%
完成

社会化网络

关于

微信订阅号

扫描微信二维码关注宁皓网,每天进步一点