Rails-通过关系表在视图上显示类别名称

时间:2019-01-02 05:23:04

标签: ruby-on-rails

我有两个表与Blog和post_categories建立关系。下面是模式:

  create_table "blogs", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.integer "status", default: 0
    t.bigint "post_category_id"
    t.index ["post_category_id"], name: "index_blogs_on_post_category_id"
    t.index ["slug"], name: "index_blogs_on_slug", unique: true
  end

  create_table "post_categories", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

现在我要做的是在我的博客index.html.erb文件上显示类别名称而不是类别ID。我做了以下事情,但是没有用:

<tbody>
    <% @blogs.each do |blog| %>
      <tr>
        <td><%= blog.title %></td>
        <td><%= blog.body %></td>
        <% PostCategory.all.each do |c| %>
          <% if c.id == blog.post_category %>
          <td><%= c.name %>
          <% end %>
        <td><%= link_to 'Show', blog %></td>
        <td><%= link_to 'Edit', edit_blog_path(blog) %></td>
        <td><%= link_to 'Destroy', blog, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>

注意:我还尝试过直接通过<td><%= blog.post_category.name %></td>访问它,但仍然无法正常工作。

任何想法如何显示类别名称而不是关联的类别ID?

2 个答案:

答案 0 :(得分:2)

根据您提供的架构,请注意PostCategory对象具有许多Blog对象

模型更改

class PostCategory < ApplicationRecord
  has_many :blogs
end

class Blog < ApplicationRecord
  belongs_to :post_category
end

查看更改,

<tbody>
  <% @blogs.each do |blog| %>
    <tr>
      <td><%= blog.title %></td>
      <td><%= blog.body %></td>
      <td><%= blog.post_category.name rescue 'No post category present for this blog' %></td>
      <td><%= link_to 'Show', blog %></td>
      <td><%= link_to 'Edit', edit_blog_path(blog) %></td>
      <td><%= link_to 'Destroy', blog, method: :delete, data: { confirm: 'Are you sure?'} %></td>
    </tr>
  <% end %>

答案 1 :(得分:1)

模型更改

class PostCategory < ApplicationRecord
  has_many :blogs
end

class Blog < ApplicationRecord
  belongs_to :post_category
end

查看更改,

<tbody>
  <% @blogs.each do |blog| %>
    <tr>
      <td><%= blog.title %></td>
      <td><%= blog.body %></td>
      <td><%= blog.post_category.try(:name) %></td>
      <td><%= link_to 'Show', blog %></td>
      <td><%= link_to 'Edit', edit_blog_path(blog) %></td>
      <td><%= link_to 'Destroy', blog, method: :delete, data: { confirm: 'Are you sure?'} %></td>
    </tr>
  <% end %>