利用多态关联

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

打开 Rails 的控制台 .. 创建一条评论 .. 使用模型的 Create 方法 .. 设置一下评论的内容 ... 再用一个 commentable_type ... 类型是 Post ... 表示这是一个给文章内容的评论 .. 再用 commentable_id 设置一下文章的 id 号 ..

Comment.create(content: 'nice ~', commentable_type: 'Post', commentable_id: 1)

再找到 id 号是 1 的这个文章内容 ... 得到它所有的评论,可以访问一下 comments .. 你会看到刚才我们给这个文章添加的评论 ...

post_1.comments

这个评论的 id 号是 1,找到这个评论 ... 使用模型的 find 方法 ..

comment_1 = Comment.find(1)

得到这个评论所属的内容,可以访问一下它的 commentable ..

comment_1.commentable

这里会显示这条评论所属的内容 ...

再去创建一个照片 ... Photo.create(title: 'sunrise')

这个照片的 id 号是 1 ... 下面我们再给它添加一个评论 ... 设置一下评论的内容 ... commentable_type 是 Photo ..commentable_id 是 1 ,

comment_2 = Comment.create(content: 'beautiful ~', commentable_type: 'Photo', commentable_id: 1)

查看一下 photo_1 所有的评论 .. 先找到它 ... .. 使用模型的 find 方法 ..

再访问一下它的 comments ... 返回的就是 id 号是 1 的这个照片内容的评论 ...

利用多态关联《 Rails:关联 》

统计

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

社会化网络

关于

微信订阅号

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