如何显示类别的名称而不是其ID?

时间:2016-09-13 20:11:41

标签: ruby-on-rails ruby

我想在Post的show.html.erb中显示类别名称。

这是它的当前代码:

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>

<p>
  <strong>Category:</strong>
  <%= @post.category_id %>
</p>

<h2>Comments</h2>
<%= render @post.comments %>

<h2>Add a comment</h2>
<%= render 'comments/form' %>

<%= link_to 'Back', posts_path %>

我如何处理这部分:<%= @post.category_id %>所以它可以显示该类别的名称?

目前的架构是:

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

  create_table "comments", force: :cascade do |t|
    t.string   "name"
    t.text     "body"
    t.integer  "post_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["post_id"], name: "index_comments_on_post_id", using: :btree
  end

  create_table "posts", force: :cascade do |t|
    t.string   "title"
    t.text     "text"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
    t.index ["category_id"], name: "index_posts_on_category_id", using: :btree
  end

  add_foreign_key "comments", "posts"
  add_foreign_key "posts", "categories"
end

目前的型号是:

发表:

class Post < ApplicationRecord
  has_many :comments
  belongs_to :category

  validates :title, presence: true
  validates :text, presence: true
end

分类

class Category < ApplicationRecord
  has_many :posts
end

注释:

class Comment < ApplicationRecord
  belongs_to :post
end

2 个答案:

答案 0 :(得分:1)

您应该访问@post的类别名称:

@post.category.name

答案 1 :(得分:0)

因为您在Post模型中使用关联belongs_to,所以您可以通过这种方式在视图中获取类别名称:

<%= @post.category.name %>