微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby on Rails 6:在视图上使用多对多关联

如何解决Ruby on Rails 6:在视图上使用多对多关联

我有一个 Post 模型和一个 Category 模型。一个帖子可以有很多分类一个分类可以用在很多帖子上。

class Post < ApplicationRecord
  belongs_to :author

  has_many :blogs
  has_and_belongs_to_many :category,through: :blogs

  has_rich_text :content
end

class Category < ApplicationRecord
  has_many :blogs
  has_and_belongs_to_many :posts,through: :blogs
end

我已经正确构建了架构表。我的问题是,如何构建包含类别的帖子列表?即,

类别:食品

  • 帖子#3
  • 帖子#6

等等

解决方法

通常,对于 has_many_and_belongs_to 关联

class Post < ApplicationRecord
  has_and_belongs_to_many :category
end

class Category < ApplicationRecord
  has_and_belongs_to_many :posts
end

这会起作用...

category = Category.first
category.posts.build({title: 'post_1',content: '...'},{title: 'post_2',content: '...'})

对于这种情况, has_and_belongs_to_many :posts,through: :blogs,

您可以建立类别以通过博客发布许多帖子,

category.blogs.build({title: 'blog_1',post_id: 3},{title: 'blog_2',post_id: 6}),

现在,category 将在保存时具有 post_3post_6

category.posts

output: [post_3,post_6]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。