2016-09-13 2 views
0

Я пытаюсь показать название категории в 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 

ответ

0

Поскольку вы используете ассоциации BELONGS_TO в сообщении модели, вы можете получить название категории по вашему мнению, таким образом:

<%= @post.category.name %> 
+0

Благодарим вас за ответ! – user273072545345

1

Вы должны получить доступ к имени @post «s категории в:

@post.category.name 
+0

Спасибо за ваш ответ! – user273072545345