ruby-on-rails - 如何在 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)
解决方案
查看has_and_belongs_to_many
指南,请注意引用没有进入categories
nor 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
并删除帖子表中对类别的引用。
推荐阅读
- python - Python config - 遍历部分并创建变量
- html - 在可编辑的 div 中插入 SVG 元素
- image - 我可以在后台运行“image.dart”功能吗
- python-webbrowser - 如何编写一个程序来帮助我在 URL 中使用 https 访问数据
- python - 如何计算 odoo 13 销售订单行上的字段?
- android - Environment.getExternalStorageDirectory() 弃用和 OBB 文件位置
- flutter - Flutter FirebaseAuth:当电子邮件地址格式错误时,SignInWithEmailAndPassword 无法处理错误
- android - 按钮现在可以在 android studio 中使用运动布局
- api - 调用 api 并在 Nodejs 中返回这些值
- python - 如何改进 ML 模型以提高准确性