Reputation: 782
I'm trying to create a query in postgres using (rails) activerecord, but can't seem to solve it.
A Company has many pages, and I'm trying to get the latest page of all companies.
I tried
Page.select('DISTINCT company_id')
which gives me 1 page of all companies. But this isn't the latest (created_at ASC)
So I tried
Page.select('DISTINCT company_id').order('created_at ASC')
which gives an error since created at isn't in the select. But if I add it, I get all records returned.
So I tried
Page.group('company_id').select('company_id').order('created_at ASC')
But this gives an error, that created_at should be in group by or aggregator function.
adding created_at to the group by, gives unwanted result (multiple pages, of the same company)
Any help?
edit:
I like it to be a scope, I need to chain the scopes later on.
Upvotes: 4
Views: 1364
Reputation: 43298
Page.order('created_at ASC').pluck(:company_id).uniq
You could try this to get an ActiveRecord::Relation
:
Page.select('max(id) as id, company_id').group(:company_id)
I would use id
to determine the "recentness" of a page instead of created_at
. The higher the id
the more recent the page is. You can simply get the highest page id
per company_id
with the code above.
Upvotes: 3