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]