N
N
nluparev2018-06-23 22:48:23
Ruby on Rails
nluparev, 2018-06-23 22:48:23

How to optimize following query in Active Record?

there is the following code:

category = Category.where(slug: params[:category]).first
result = Slide.where(category_id: category.id)

it is necessary to select some instances of models using the value of the foreign key of the parent table, or in other words, the model to which it belongs, belongs_to . The Category model is selected using the url parameter and then its id is used as the foreign key value to be selected by an instance of the Slide models.
in SQL I achieved the same results as follows
SELECT *
FROM
  slides AS sl
INNER JOIN
  categories AS ct
ON
  sl.category_id = ct.id
WHERE ct.slug = 'home-work';

or in this way
SELECT *
FROM slides
WHERE category_id IN (SELECT id FROM categories WHERE slug = 'home-work');

The 2nd option is closer in essence to what happens in the Ruby code above.
is it possible to somehow optimize the Ruby code to select the necessary Slide so that it is executed on the SQL side as one query and not two separate ones?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pazzik, 2018-06-23
@nluparev

Slide.includes(:categories).where(category: { slug: params[:category] })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question