How can I load the most recent object in a has_many relationship?

I have a rails 3 application that has models such as categories and posts.

Category

has_many: posts

Message

belongs to_to: category

I want to be able to display a list of categories with the last message located next to it, without scrolling and getting into the database for each category and only discarding one message for each category.

I want to do the same thing that asks this question - SQL join: selecting the latest records in a one-to-many relationship , but hopefully using Active Record.

Is this really a stupid thing? Should I just drop all posts for a category while trying to load them? I was worried about performance, so I started researching this.

+3
1

, , . , , . , , :

class Category < ActiveRecord::Base
  has_one :last_post, :class_name => "Post", :foreign_key => "category_id", :order => "created_at desc"
end

:

Category.includes(:last_post).all

, - , sql, , category.last_post . sql, :

SELECT `categories`.* FROM `categories`
SELECT `posts`.* FROM `posts` WHERE (`posts`.category_id IN (1,2)) ORDER BY created_at desc
+3

Source: https://habr.com/ru/post/1786578/


All Articles