首页 > 解决方案 > 如何在 Rails 中为一篇文章添加多个类别

问题描述

我想制作一个功能来显示具有特定类别的帖子,A,B,C ...,其中可能有多个类别。目前,我只能添加一个。

我怎样才能添加更多并显示它们?

这是迁移:

class CreateCategories < ActiveRecord::Migration[6.0]
  def change
    create_table :categories do |t|
      t.string :name
      t.text :description
      t.boolean :display_in_navbar, default: true

      t.timestamps
    end
  end
end


class CreatePosts < ActiveRecord::Migration[6.0]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.string :author
      t.boolean :featured
      t.integer :likes
      t.string :source
      t.references :category, null: false, foreign_key: true

      t.timestamps
    end
  end
end

我的模型:

class Category < ApplicationRecord
  has_and_belongs_to_many :posts
end


class Post < ApplicationRecord
  has_and_belongs_to :categories
end

和观点:

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Body</th>
      <th>Author</th>
      <th>Featured</th>
      <th>Likes</th>
      <th>Source</th>
      <th>Category</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.body %></td>
        <td><%= post.author %></td>
        <td><%= post.featured %></td>
        <td><%= post.likes %></td>
        <td><%= post.source %></td>
        <td><%= post.category.name %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

这是 _form.html.erb:

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Body</th>
      <th>Author</th>
      <th>Featured</th>
      <th>Likes</th>
      <th>Source</th>
      <th>Category</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.body %></td>
        <td><%= post.author %></td>
        <td><%= post.featured %></td>
        <td><%= post.likes %></td>
        <td><%= post.source %></td>
        <td><%= post.category.name %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

和_post.json.jbuilder:

json.extract! post, :id, :title, :body, :author, :featured, :likes, :source, :category_id, :created_at, :updated_at
json.url post_url(post, format: :json)

标签: ruby-on-railsruby

解决方案


查看has_and_belongs_to_many指南,请注意引用没有进入categoriesnor posts,而是指向中间的连接表,在这种情况下categories_posts

create_table :categories_posts, id: false do |t|
  t.belongs_to :category
  t.belongs_to :post
end

或者用create_join_table做等效的。

create_join_table :categories, :posts do |t|
  t.index :category_id
  t.index :post_id
end

并删除帖子表中对类别的引用。


推荐阅读