Ruby Question

how to show the name of category instead of its ID?

I am trying to have the category name show up in the Post's show.html.erb ... this is the current code for it so far:

<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 %>


How do I deal with this part:
<%= @post.category_id %>
so it can show the name of the category instead?

Current schema is:

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


Current models are:

Post

class Post < ApplicationRecord
has_many :comments
belongs_to :category

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


Categories

class Category < ApplicationRecord
has_many :posts
end


Comment

class Comment < ApplicationRecord
belongs_to :post
end


Please let me know if there's any other code I need to include

Thank you

Answer

Because you are using association belongs_to in Post model, you can get the category name in your view this way:

<%= @post.category.name %>