Select from multiple tables in Rails

Say I have apples, oranges and melons, and each has a "created_at" column. How can I build an ActiveRecord / SQL query to find the 10 most recent apples, oranges and melons? Is there an elegant way to do this?

+3
source share
2 answers

If you have these types in separate tables, I don’t think you can do this in a single SQL query.

You can find identifiers and types of recent entries, such as:

SELECT * FROM
(SELECT 'Apple' AS class, id, created_at FROM apples LIMIT 10
UNION
SELECT 'Orange' AS class, id, created_at FROM oranges LIMIT 10
UNION
SELECT 'Melon' AS class, id, created_at FROM melons LIMIT 10) AS most_recent
ORDER BY created_at
LIMIT 10;

Then use these records to retrieve specific objects by id.

, , Inheritance, . , . Fruit.find order limit, , .

Rails 2:

Fruit.find(:all, :order => "created_at", :limit => 10)
+2

,

Apples.joins(:oranges).joins(:melons).order("apples.created_at,oranges.created_at,melons.created_at DESC").limit(10)
0

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


All Articles