Answer the question
In order to leave comments, you need to log in
How to correctly get the value from the table?
Hello everyone, I can not write correctly.
There is a post table with a link to the post_categories table by id.
I'm trying to get the category name by its id in the post table (post_category_id)
<% @post.each do |post| %>
<%= PostCategory.select('name').where(id: post.post_category_id) %>
<% end %>
SELECT name FROM `post_categories` WHERE id = 1
#<PostCategory::ActiveRecord_Relation:0x00000006c62ba8>
Answer the question
In order to leave comments, you need to log in
I advise you to read what ActiveRecord::Relation is to understand what rail methods return to you.
But in any case, you should never do as you have written, spawning requests in a cycle is very bad for performance. If you want to display the category name next to each post, then do this:
# В контроллере:
@posts = Post.includes(:post_category)
# Во вьюхе:
<% @posts.each do |post| %>
<%= post.post_category.name %>
<% end %>
guides.rubyonrails.org/active_record_querying.html
Everything is very clear.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question