B
B
bismoney2015-11-04 16:25:26
Ruby on Rails
bismoney, 2015-11-04 16:25:26

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
I want to receive a request
#<PostCategory::ActiveRecord_Relation:0x00000006c62ba8>

How right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem Pyankov, 2015-11-04
@bismoney

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

M
Mikhail Osher, 2015-11-04
@miraage

guides.rubyonrails.org/active_record_querying.html
Everything is very clear.

V
Veniamin Chebotarev, 2015-11-04
@bj7smth

posts.each do |post|
post.post_category.name
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question